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>
usingnamespace 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!
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.
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 longdouble 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.