Half an hour ago, I made a simple factorial calculator that takes non-zero integers as inputs. After testing it for some values, I noticed that it only work properly until 12!.
I haven’t been programming for some months now, and still am a beginner to be honest. I decided to use recursion so I could get back in to “programming mode” faster (my preference).
I checked and modified it for almost an hour now. I don’t really know what is wrong with my algorithm.
This is my code:
#include <iostream>
using namespace std;
int factorial(int);
int main()
{
int usrInput = 0; //initialize input variable
cout << "Please input the factorial you want to calculate: ";
cin >> usrInput;
while(usrInput < 1)
{
cout << "Please input a valid number: ";
cin >> usrInput;
} //end while
cout << "\nAnswer: " << factorial(usrInput) << '\n';
return 0;
}
int factorial(int n)
{
int product = n;
if(n < 2)
product = 1;
else
{
product *= factorial(n-1);
cout << "\n" << product; //debugging line
} //end if else
return product;
}
You exceed limits of int. 13! = 6227020800, int only covers -2147483648 .. 2147483647. Use bigger type (eg. __int64), double (but you’ll lose precision) or implement (or use) big number library.