The factorial of an integer n, written n!, is simply the product of all the integers from 1 to n. For
example 5! = 1*2*3*4*5 = 120. Write a program to calculate the factorial of integers from 1 to n
where n is taken from the user. What is the maximum value of factorial that you can
calculate for int data type? Is there any difference between the maximum value of factorial for
unsigned and signed int?
C++ code:
#include <iostream>
using namespace std;
int main() {
unsigned int n;
unsigned int factorial = 1;
cout << "Enter a positive integer: ";
cin >> n;
if (n < 0)
cout << "Error! Factorial of a negative number doesn't exist.";
else {
for(int i = 1; i <= n; ++i) {
factorial *= i;
}
cout << "Factorial of " << n << " = " << factorial;
}
cin>>factorial;
return 0;
}
What is the maximum value of factorial that you can calculate for int data type?
Answer:
Integers typically requires 4 bytes of memory space and ranges from -2147483648 to 2147483647.
The factorial of 16 = 2004189184. So, it is the maximum value of factorial that you can calculate for int data type.
Is there any difference between the maximum value of factorial for unsigned and signed int?
Answer:
unsigned int typically requires 4 bytes of memory space and ranges from 0 to 4294967295
signed int typically requires 4 bytes of memory space and ranges from -2147483648 to 2147483647
The maximum value of factorial for unsigned and signed int is the factorial of 17 = 4006445056
Yes, there is difference between the maximum value of factorial for unsigned and signed int.
Comments
Thank you so much. Your answer is really a big help to me.
Leave a comment