Answer :
Answer:
The solution code is written in C++
- #include <iostream>
- using namespace std;
- int main()
- {
- int num;
- signed int factorial = 1;
- cout<<"Input a number: ";
- cin>> num;
- if(num >= 0 && num <30){
- for(int i = num; i > 0; i--){
- if(factorial * i < 2147483647 && factorial > 0){
- factorial *= i;
- }else{
- cout<<"Can't handle this";
- return 0;
- }
- }
- cout<<factorial;
- }
- return 0;
- }
Explanation:
Firstly, let's create variable num and factorial to hold the value of input number and the factorial value. The variable factorial is defined with a signed int data type (Line 7-8).
Next prompt user input a number and do input validation (Line 10 -13). Then create a for-loop to calculate the factorial of input number (Line 15 - 26). Within the loop, create an if-else statement to check if the factorial of n is more than the limit, if so display the message "Can't handle this". Otherwise, the program will just print out the factorial after completing the loop (Line 28).
Answer:
Python code along with step by step comments is provided below.
Python Code with Explanation:
# get input from the user
num = int(input("Enter a number: "))
factorial = 1
# check if the number is within the allowed range
if num>=0 and num<=30:
# if number is within the range then run a for loop
for i in range(1,num + 1):
# this is how a factorial is calculated
factorial = factorial*i
# now check if the result is withing the limit or not
if factorial>2147483647:
# if result is not within the limit then terminate the program
print("Sorry, cant handle the result")
exit()
# if result is within the limit then print the result
print("The factorial of",num,"is",factorial)
else:
# if input is not withing the range then print wrong input
print("Sorry, Wrong input")
Output Results:
Enter a number: 10
The factorial of 10 is 3628800
Enter a number: 15
Sorry, cant handle the result
Enter a number: 35
Sorry, Wrong input


