In this challenge you will write a recursive function that returns the value of
ID: 3932804 • Letter: I
Question
In this challenge you will write a recursive function that returns the value of n!.
Start by writing the base case:
if n is zero, then factorial should just return the value 1.
Once implemented, uncomment the Program.assertEqual() for factorial(0) at the bottom to verify that the test assertion passes.
var factorial = function(n) {
// base case:
// recursive case:
};
println("The value of 0! is " + factorial(0) + ".");
println("The value of 5! is " + factorial(5) + ".");
//Program.assertEqual(factorial(0), 1);
//Program.assertEqual(factorial(5), 120);
Explanation / Answer
var factorial = function(n) {
// base case
if(n==0)
return 1;
else
return n*factorial(n-1);
};
println("The value of 0! is " + factorial(0) + ".");
println("The value of 5! is " + factorial(5) + ".");
Program.assertEqual(factorial(0), 1);
Program.assertEqual(factorial(5), 120);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.