Why is it only working for small ints?

Hey guys, just started programming again and got a question about my code. I was doing this exercise: Write a program that asks the user to type the value of N and computes N!. So i made this program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

using namespace std;

int main(){

int n,m =1;
cin >> n;
for(int i = n; i !=0 ; i--){
    m=m*i;
}
cout << m << endl;

return 0;
}
  


It works but only til the number 16, If you go above it it wil give a negative output. I wondered why, hope you guys could help me!
Do you realize how quickly N! grows? Not even a 64-bit integer type (e.g. long long) will be able to handle more than N=20.

    N                      N!
    1                       1
    2                       2
    3                       6
    4                      24
    5                     120
    6                     720
    7                    5040
    8                   40320
    9                  362880
   10                 3628800
   11                39916800
   12               479001600
   13              6227020800
   14             87178291200
   15           1307674368000
   16          20922789888000
   17         355687428096000
   18        6402373705728000
   19      121645100408832000
   20     2432902008176640000


Your program seems to give the correct values so I think you can feel you have completed the exercise. If you really want you could output an error message if the user inputs a value of N that is larger than your program can handle. You might want to do the same if the user inputs a negative value, or some other value that is not an integer.
Last edited on
Alright thanks man, was just wondering if it was a error in the code. Now I can continue :D
Another angle on this. A cheap pocket calculator can give a result for factorials up to 69!. The point being, it uses floating-point rather than integer calculation. Using type double or long double you could go rather further than that. Of course if you need both large numbers and full precision then none of the built-in types will suffice - there are libraries available to handle large numbers.
Topic archived. No new replies allowed.