Latest news:
Sahih al-Bukhari (সহীহ বুখারী) is a free Hadith application for android. This application is advertisement free. Download now https://play.google.com/store/apps/details?id=com.akramhossin.bukharisharif
Recursive Method for Calculating Factorial
factorial(N) = {1/n X factorial(N-1) N ≤ 1/otherwise
Function Description
Complete the factorial function in the editor below.
Be sure to use recursion.
factorial has the following paramter:
Returns
Note: If you fail to use recursion or fail to name your recursive function factorial or Factorial, you will get a score of 0
Input Format
A single integer n,(the argument to pass to factorial).
Constraints
2 ≤ n ≤ 12
Sample Input
3
Sample Output
6
Explanation
Consider the following steps. After the recursive calls from step 1 to 3, results are accumulated from step 3 to 1.
1.factorial(3) = 3 x factorial(2) = 3 x 2 = 6
2.factorial(2) = 2 x factorial(1) = 2 x 1 = 2
3.factorial(1) = 1
PHP Solutions:
// Complete the factorial function below.
function factorial($n) {
if ($n == 0) {
return 1;
} else {
return $n * factorial($n - 1);
}
}
$fptr = fopen(getenv("OUTPUT_PATH"), "w");
$stdin = fopen("php://stdin", "r");
fscanf($stdin, "%d\n", $n);
$result = factorial($n);
fwrite($fptr, $result . "\n");
fclose($stdin);
fclose($fptr);
Views : 609