How can I get this recursive method to return 1
on calling 0!
without testing for a base case, that is without doing an if-else
for 0 and 1.
public static long f( number ){
if ( number <= 1 ){ // test for base case
return 1; // base cases: 0! = 1 and 1! = 1
}
else{ return number * f( number - 1 ); }
}
I don't want to check for base cases. Is this possible?
Using an if-else or ? :
is the best solution. I.e. anything els eis likely to be worse.
public static long f(int n){
try {
return 0 / n + n * f(n-1);
} catch(ArithmeticException ae) {
return 1;
}
}