Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

1. ## 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*(\$n-1)*(\$n-2))); } \$summation = factorial(3); print \$summation; ?> ```
This obviously works for 3!, but its not true for all real positive integers. I would like to make a function that allows me to substitute any number for \$n and then outputting the correct factorial value.

Tokio

• PHP Code:
``` <?phpfunction factorial(\$n) {if (\$n == 0) return 1;        return \$n * factorial(\$n - 1);}\$summation = factorial(3);print \$summation;?> ```
You need to make it recursive.

• ## Users who have thanked _Aerospace_Eng_ for this post:

tokio (05-11-2009)

• Originally Posted by _Aerospace_Eng_
PHP Code:
``` <?php function factorial(\$n) { if (\$n == 0) return 1;         return \$n * factorial(\$n - 1); } \$summation = factorial(3); print \$summation; ?> ```
You need to make it recursive.
Sup Aerospace, and thinks for the int man. But, i think its an error in the code, and i couldn't depict any fallacies. Did the code worked when you executed it?

• 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!

This is for 10!

• ## Users who have thanked _Aerospace_Eng_ for this post:

tokio (05-11-2009)

• Originally Posted by _Aerospace_Eng_
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!

This is for 10!
Ok, i copied and pasted the code to a blank file on my server and it works. I originally pasted it into a file that i had previous code that appeared to work fine, but i must of had some errors that i couldn't find.

• Just a while ago had similar need..

Except i had to get all factorials till given number, so here if someone needs the code

PHP Code:
``` <?phpfunction 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;?> ```
A bit messy, but does the trick :\

Max, 170

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•