Why i can't do that? | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
0

Why i can't do that?

Hi everyone! at this code : https://code.sololearn.com/csQ8GVyktqLb/?ref=app Why i can't write factorial(n-2)or another number instead of factorial(n-1). Help me.

11th Aug 2018, 3:15 PM
Feres
Feres - avatar
4 ответов
+ 1
Try the following int factorial(int n) { if (n==1) { return 1; } else { if (n>2) return n*(n-1)*factorial(n-2); else return n * factorial(n-1); } }
11th Aug 2018, 3:56 PM
Микола Федосєєв
Микола Федосєєв - avatar
0
well... its pretty simple when you think about it this is your code #include <iostream> using namespace std; int factorial(int n) { if (n==1) { return 1; } else { return n * factorial(n-1); } } int main() { cout << factorial(7); } the problem here is that when change (n-1) to (n-2) its going to work only on odd numbers because when you keep substracting an odd number by 2 like number 7 it'll eventually become 1 which makes the condition (n==1) activate and stop substracting BUT when its an even number (int n ) won't become equall to 1 which makes it loop forever
14th Sep 2018, 5:11 PM
Gildin
0
a good way to fix it is to change the if condition from (n==1) to n less than or equall to 1(n<=1)
14th Sep 2018, 5:14 PM
Gildin
0
One more variant: int factorial(int n) { if (n<=2) return n; return factorial(n-2)*(n-1)*n; }
14th Sep 2018, 10:20 PM
Микола Федосєєв
Микола Федосєєв - avatar