Question

I made this simple program that calculates the factorial of a given number. For a number n it is

n * (n-1) * (n-2) ....* (n-(n-1))

Here is the code:

#include<stdio.h>
int main()
{
int i,n;
long fact=1;
printf("Enter a number: \t")
scanf("%d",&n);
for(i=0; i<=(n-1); i++)
{    if( n==0 || n==1)
      fact =1;
      else
      fact*=i;
 }
 return 0;
 }

I realized that the program crashes when the user inputs a large number.(which is logical)

  1. I want the limit of this number. (i.e the max number that can be inputed by the user without crashing the program.)
  2. Is there a way to increase this number?

Any help is appreciated.

Was it helpful?

Solution

generally in c and c++ , the minimum requirements are

signed char: -2^07+1 to +2^07-1
short:       -2^15+1 to +2^15-1
int:         -2^15+1 to +2^15-1
long:        -2^31+1 to +2^31-1
long long:   -2^63+1 to +2^63-1

so to find out the limit of the number that can be entered, you would have to look for two numbers whose factorials fall just below and just above the range of long, i.e., 2^31 - 1 in the minimal case

to increase this limit, you might consider using long long

or maybe unsigned long long

OTHER TIPS

try to use scanf("%ld",&n)

or scanf("%lld",&n), also do with printf or maybe use strings and arrays to work with big numbers

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top