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.
4 Respuestas
+ 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);
}
}
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
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)
0
One more variant:
int factorial(int n) {
if (n<=2) return n;
return factorial(n-2)*(n-1)*n;
}