Write a program which reads in a single integer 0 <= n < 30 and prints out the factorial of n. Factorials get very big very quickly and can easily exceed the limits of a signed int that uses 4 bytes. If the value of factorial of n is too large to be stored in an int (>2,147,483,647), your program should print Can't handle this.

Answer :

teobguan2019

Answer:

The solution code is written in C++

  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5.    int num;
  6.    signed int factorial = 1;
  7.    
  8.    cout<<"Input a number: ";
  9.    cin>> num;
  10.    
  11.    if(num >= 0 && num <30){
  12.        
  13.        for(int i = num; i > 0; i--){
  14.            
  15.            if(factorial * i < 2147483647 && factorial > 0){
  16.                
  17.                factorial *= i;
  18.                
  19.            }else{
  20.                
  21.                cout<<"Can't handle this";
  22.                return 0;
  23.            }
  24.        }
  25.        cout<<factorial;
  26.    }
  27.    return 0;
  28. }

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

${teks-lihat-gambar} nafeesahmed
${teks-lihat-gambar} nafeesahmed
${teks-lihat-gambar} nafeesahmed

Other Questions