+ 1
Valid recursion question
In the c# callenges, one question asks for filling a valid recursion, and the final answer is as follows: public static int fact (int num) { if (num ==1) return 1; return num*fact (num -1); } Now, if this is the case, if my input is -1, for example, don't i get an infinite loop? Shouldn't it be ' if (num <= 1) '?
4 Respostas
+ 3
That function represents factorial in math. Factorial is valid only for positive numbers, special case 0! = 1. So calculation of factorial with negative numbers doesn't make any sense.
+ 3
Yes, condition should be changed if you want to calculate with negative numbers. But there's no need to check for 0 (for normal factorial in math) because it is known that 0! = 1. That's why the base case is num = 1.
+ 3
German Pais
one of the laws of recursion : A recursive algorithm must have a base case.
If your input breaks this, you've simply made a
while(true) loop
0
I understand, and that's totally true. Nevertheless, I still can pass a negative number as a parameter and get an infinite loop? For that case, perhaps there should be another conditional for 0 and lesser numbers, right?