Write a program that uses a function for to evaluate the factoriales of the points of the 1 to 5. Show The results in format to tabulate. What dificult might prevent that you were calculating the factorial of 20?
//Ejercicio 5.9;Instrucciones de control II
//Luis Fernando Pinzon
//21/09/2018
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int main(int argc, char** argv)
{
//Factorial
int factorial = 1;
int user;
cout << "enter a number: ";
cin >> user;
cout << endl;
for(int counter = 1; counter <= user; counter++)
{
factorial *= counter;
cout << factorial << "! " << endl;
// From here, the number 12 the collector does not show beyond of 10 numbers, so then the following results are inaccurate.
}
cout << "the factorial number " << user << " is " << factorial << endl;
return 0;
}
enter a number: 20
1!
2!
6!
24!
120!
720!
5040!
40320!
362880!
3628800!
39916800!
479001600!
1932053504!
1278945280!
2004310016!
2004189184!
-288522240!
-898433024!
109641728!
-2102132736!
the factorial number 20 is -2102132736
The maximum value for an int type variable is 2147483647. factorial *= counter; is making your value grow exponentially, hence why you reach that limit very quickly!
#include <iostream>
#include <limits>
#include <typeinfo>
#include <cmath>
usingnamespace std;
template <typename T> void maxFactorial()
{
T maximum = numeric_limits<T>::max();
int N = 1;
while( tgamma( N + 1 ) <= maximum ) N++;
N--;
cout << "Type " << typeid( T ).name() << "; maximum value: " << maximum << "; maximum factorial: " << N << '\n';
}
int main()
{
maxFactorial<short>();
maxFactorial<unsigned>();
maxFactorial<int>();
maxFactorial<long>();
maxFactorial<longlong>();
maxFactorial<unsignedlonglong>();
}
Type s; maximum value: 32767; maximum factorial: 7
Type j; maximum value: 4294967295; maximum factorial: 12
Type i; maximum value: 2147483647; maximum factorial: 12
Type l; maximum value: 2147483647; maximum factorial: 12
Type x; maximum value: 9223372036854775807; maximum factorial: 20
Type y; maximum value: 18446744073709551615; maximum factorial: 20
Makes me feel that factorial( N ) isn't all that useful a function.
thank you all, why line number 27th hasn't any sense? it´s supposed to show up the factorial nomber.
by the way, there are lots of new information about that simple problem guys. but i don't sure about limitations on differents systems. isn´t it supposed to all systems has a ordinary dafault characteristics?
Line 27 didn't make sense as output, that is all. The '!' is applied to the number whose factorial was being taken, not the result. e.g. 4! = 24, not 24!, which we've just ascertained that you couldn't compute (as an int).
No, different systems have different characteristics. The c++ standard often requires them to have minimum levels of accuracy, but doesn't set the maximum.