|
|
| |
|
|
Write a function that, given a number as input, returns the factorial of that number.
The factorial of a number 'n' is the product of all positive integers less than or equal
to 'n'. So, the factorial of 6 would be 6*5*4*3*2*1 = 720. The factorial of 0 is 1.
|
|
This question was asked during an interview with NCR.
The factorial for a number 'n' would be n*(n-1)*(n-2)...*1.
Problems like this that have a repetitive pattern tend to
be more easily solved by using recursion.
Taking a closer look at the problem, we could also say that the
factorial of a number 'n' is also equivalent to the number 'n' multiplied
by the factorial of 'n-1'. With that in mind, we can write the following Java method:
public int Factorial(int n)
{
return n * Factorial(n-1);
}
One thing is obviously missing from the code above. If we were to pass in a number,
then the function simply will not stop executing! We need to add a boundary condition, but
what should it be? Because factorials are only defined for non negative integers, it makes
sense to use 0 as our boundary case. So, if 'n' (the number passed in to the function)
ever equals 0 then we will return a 1, because the factorial of 0 is 1. Now, we have this:
public int Factorial(int n)
{
if (n == 0)
return 1;
else
return n * Factorial(n-1);
}
We've now found our answer - all that work and the code is suprisingly simple! This question
is a favorite for interviewers, and it's a good one to know.
|
|
|