this is the classic example of a program where recursion is the most efficient way to calculate it. also im pretty sure C++ starts to be incorrect starting at around 15! or so.
hint: the base case is when you have to multiply by 1 :)
#include <iostream>
usingnamespace std;
int factorial (int x);
int main ()
{
int n;
cout<<"Enter number: ";
cin>>n;
int fact;
fact = factorial(n);
cout<<"The factorial of number: "<<n<<" is: "<<fact<<endl;
cin.get(); cin.get();
return 0;
}
int factorial(int x)
{
int i;
int F=1;
for (i = 1; i <= x; i++)
F*=i;
return F;
}
...C++ starts to be incorrect starting at around 15.
That is wrong statement. Its not C++ that is incorrect, you must use type that can accept/hold large numbers. See (for example) this: http://www.cplusplus.com/reference/std/limits/numeric_limits/
Make your own type that can represent these numbers or use some library for this purpose.
whats your point buffbill? a recursive function is the most efficient. factorial 27 is probably out of the range of an int anyways, and 51 certainly is.
typedef whatever_you_want fact_type;
fact_type factorial(fact_type n) //I HATE camel casing for functions. How come you guys like it so much???
{
if (n == 0) return 1;
if (n < 3) return n;
return n * factorial(n -1);
}