Recursion

0 Sahaj _ · June 19, 2015
I just created the factorial program as Bucky taught in the tutorial.


#include <iostream>
using namespace std;

int fact(int x) {
if(x == 1) {
return 1;
}else{
return x*fact(x-1);
}
}

int main() {
int a;
cout << "Please enter the number  : ";
cin >> a;
cout << "The factorial of " << a << " is : " << fact(a);
}


My question is that why one can't get correct answer after the input is 16? The value that pops out as answer is negative. And 0 after 20.

Thanks!

Post a Reply

Replies

Oldest  Newest  Rating
0 Sahaj _ · June 19, 2015
Thanks Alan!
+2 Alan Johnson · June 19, 2015
Because the answer to anything higher than 16 factorial is too big a number to fit into a standard int type.

If you make your int unsigned it can store bigger numbers and thus work out bigger factorial calculations. This would look like:

#include <iostream>

using namespace std;

unsigned int fact(unsigned int x) {
if (x == 1) {
return 1;
} else {
return x*fact(x-1);
}
}

int main() {
unsigned int a;
cout << "Please enter the number : ";
cin >> a;
cout << "The factorial of " << a << " is : " << fact(a);
}

  • 1

C++

107,232 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator