220k views
2 votes
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.

2 Answers

0 votes

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

Write a program which reads in a single integer 0 <= n < 30 and prints out the-example-1
Write a program which reads in a single integer 0 <= n < 30 and prints out the-example-2
Write a program which reads in a single integer 0 <= n < 30 and prints out the-example-3
User Enkum
by
6.1k points
4 votes

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. cout<<"Input a number: ";
  8. cin>> num;
  9. if(num >= 0 && num <30){
  10. for(int i = num; i > 0; i--){
  11. if(factorial * i < 2147483647 && factorial > 0){
  12. factorial *= i;
  13. }else{
  14. cout<<"Can't handle this";
  15. return 0;
  16. }
  17. }
  18. cout<<factorial;
  19. }
  20. return 0;
  21. }

Step-by-step 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).

User Imgen
by
4.8k points