Valid recursion question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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) '?

24th Aug 2018, 1:56 PM
German Pais
German Pais - avatar
4 Answers
+ 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.
24th Aug 2018, 2:28 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 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.
24th Aug 2018, 2:53 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 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
24th Aug 2018, 3:08 PM
E_E Mopho
E_E Mopho - avatar
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?
24th Aug 2018, 2:47 PM
German Pais
German Pais - avatar