Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Calculate Factorial

Status
Not open for further replies.

mikeadn

Programmer
Jan 21, 2004
14
0
0
US
How can you populate a table with factorial values for a population size of 1 - 200?

Mike Cormier
May God bless everything you do...
 
Factorials are multiplication of all integers less than or equal to the principal, right?

1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720

The cleanest way I can think of is to create a user-defined function that you can use in SELECTs and such:

Code:
CREATE FUNCTION dbo.fnFactorial( @principal int )
RETURNS int
AS
BEGIN
  DECLARE @factorial int, @cntr int
  SELECT @cntr = 1, @factorial = 1
  
  WHILE @cntr <= @principal
     SELECT @factorial = @factorial * @cntr,
            @cntr = @cntr + 1
  
  RETURN @factorial
END
-----------------------------
SELECT dbo.fnFactorial(6)


--John [rainbow]
-----------------------------------
Behold! As a wild ass in the desert
go forth I to do my work.
--Gurnie Hallock (Dune)
 
returns int" won't do, john

200! is an extremely large number :)

788657867364790503552363213932185062295135977687173263294742533244359449963403342920304284011984623904177212138919638830257642790242637105061926624952829931113462857270763317237396988943922445621451664240254033291864131227428294853277524242407573903240321257405579568660226031904170324062351700858796178922222789623703897374720000000000000000000000000000000000000000000000000

source:
sorry for blowing up the layout of this forum page

rudy | r937.com | Ask the Expert | Premium SQL Articles
SQL for Database-Driven Web Sites (next course starts May 8 2005)
 
Exactly how many digits:

Code:
create function howmanyfactdigits(@n int)
returns int
as
begin
	declare @digits float; set @digits = 0

	while @n > 1
	begin
		set @digits = @digits + log10(@n)
		set @n = @n-1
	end

	return 1 + convert(int, @digits)
end



------
heisenbug: A bug that disappears or alters its behavior when one attempts to probe or isolate it
schroedinbug: A bug that doesn't appear until someone reads source code and realizes it never should have worked, at which point the program promptly stops working for everybody until fixed.
 
Thanks rudy. Float is being hateful too. I was more concerned with the factorial function than populating the table (bad boy, no spanking). I don't think there is any data numeric data type that will hold this number.

Mike, can you decrease the range of values you want?

--John [rainbow]
-----------------------------------
Behold! As a wild ass in the desert
go forth I to do my work.
--Gurnie Hallock (Dune)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top