As we all know there is memory limitation in C. If we want to store number which is more than of 4 byte we cannot use **int **data type. We can use **long **data type to store value which is upto 8 byte. What after that?. If our value is of more than 8 bytes then we have to implement our own method to store value.

Here is the implementation of calculating factorial for large numbers like 100!

Explanation:

This program works on basic method of multiplication of a two numbers.

1234

X 15

Ans: **18510**

Steps are:

Step Digit Carry

15*4 = 60; 0 6

(15*3)+6=51 1 5

(15*2)+5=35 5 3

(15*1)+3=18 8 1

After this carry digits are extracted and stored in array. ( if our carry was 25 then we must extract 2 and 5 then store it in array )

So output is: 18510

In program:

Array of 200 lengths is taken to store digits of multiplication result.

Index variable indicates the length of output..

tmp is used to store carry value;

————————————————————————————————————————–

Calculating Factorial of large numbers in c

Her we have taken array size of 200 so we can calculate factorial of a number whose digits are 200. if you want to calculate for more than 200 just increase the size of array.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
/* C code to implement factorial of large number */ #include<stdio.h> int main(){ int a[200],index,i,j,n,tmp,counter=0; printf("\n Enter the no : "); scanf("%d",&n); a[0]=1; index=0; //Calculation Loop for(j=n;j>=2;j--){ tmp=0; /* This Loop is used to multiply the numbers */ for(i=0;i<=index;i++){ tmp=(a[i]*j)+tmp; // here tmp is carry digir which should be added to next multiplied value a[i]=tmp%10; // Extracting last digit of number tmp=tmp/10; // Extracring carry digir } // This loop helps you to extract digits from last calculated carry digits /* Supposse last carry digit is 25 then we must extract each digit( 5 & 2) and store it into array */ while(tmp>0){ a[++index]=tmp%10; tmp=tmp/10; } } //Loop to print output of calculated factorial printf("\n The factorial of %d is : \n",n); for(i=index;i>=0;i--) printf("%d",a[i]); return 0; } |