Enjoy an ad free experience by logging in. Not a member yet? Register.

Results 1 to 6 of 6
Thread: Factorial function

05112009, 05:52 AM #1
 Join Date
 Jun 2008
 Location
 Jupiter
 Posts
 49
 Thanks
 8
 Thanked 0 Times in 0 Posts
Factorial function
I know php have their built in mathematical functions, but im trying to write my own mathematical function so i can learn the basics for php. What im trying to do is write a mathematical function so that it will work for all real positive integers. The factorial operator is denoted with (!). An example is 3! which equals 3*2*1. Here is what i came up with thus far:
PHP Code:<?php
function factorial($n) {
return (($n*($n1)*($n2)));
}
$summation = factorial(3);
print $summation;
?>
Tokio
05112009, 06:46 AM
#2
 Join Date
 Dec 2004
 Location
 In a place far, far away...
 Posts
 19,291
 Thanks
 2
 Thanked 1,043 Times in 1,019 Posts
You need to make it recursive.PHP Code:
<?php
function factorial($n) {
if ($n == 0) return 1;
return $n * factorial($n  1);
}
$summation = factorial(3);
print $summation;
?>
If you are getting paid to do a job, don't ask for help on it!
Users who have thanked _Aerospace_Eng_ for this post:
tokio (05112009)
05112009, 07:57 AM
#3
 Join Date
 Jun 2008
 Location
 Jupiter
 Posts
 49
 Thanks
 8
 Thanked 0 Times in 0 Posts
05112009, 08:01 AM
#4
 Join Date
 Dec 2004
 Location
 In a place far, far away...
 Posts
 19,291
 Thanks
 2
 Thanked 1,043 Times in 1,019 Posts
I just tested it and it worked fine. I put in 3 and got 6, then I put in 10 and got 3628800
If you notice in these google results that its correct.
This is for 3!
http://www.google.com/search?q=3+fac...ient=firefoxa
This is for 10!
http://www.google.com/search?q=10+fa...ient=firefoxa
If you are getting paid to do a job, don't ask for help on it!
Users who have thanked _Aerospace_Eng_ for this post:
tokio (05112009)
05112009, 08:14 AM
#5
 Join Date
 Jun 2008
 Location
 Jupiter
 Posts
 49
 Thanks
 8
 Thanked 0 Times in 0 Posts
05112009, 02:49 PM
#6
Just a while ago had similar need..
Except i had to get all factorials till given number, so here if someone needs the code
A bit messy, but does the trick :\PHP Code:
<?php
function factiorial($n) {
$result = "";
$m=1;
while ($i <= $n) {
++$i; $result .= "For $i!"; $m *= $i; $result .= " result is $m <br>";
}
return $result;
}
$result = factiorial(5);
print $result;
?>
Max, 170
Last edited by funnymoney; 05112009 at 02:51 PM.