Here is my algorithm :-
You know to calculate factorial of a number, you should multiply all numbers from 1 to itself, for example:
1000! = 1*2*3*……*998*999*1000 There is no variable in any programming language that can store the result of this multiplication exactly; except storing in scientific notation. Because of sequential multiplication's huge result, finding a new strategy or mechanism is necessary.In my recommended algorithm, the number is not looked at as a number, instead it is treated as sequential digits where each one has its own numerical value. In fact, an array of digits is available. Each time, the second numberis multiplied by each digit of the first number (index of array) and then added with carry number up from the previous multiplication.
This process is shown, for example 12!:
12! = 11! * 12 11! = 39916800 12! = 479001600 http://cboard.cprogramming.com/1000-...es/article.jpg
- If the result is less than 10, the result will be placed in the cell of array.
- If it is equal to or greater than 10, it will be divided by 10 and then the remainder will be placed in the array's cell and quotient placed in variable that will be added with next multiplication's response.
Note: Notice that all the numbers are stored from end of array, the same as normal calculation (real calculation).
Code:
#include<stdio.h>
2 int main()
3 {
4 int t,count,n,p,count1,i,carry=0,total,k=0;
5 int array[500];
6 scanf("%d",&t);
7 for(count=1;count<=t;count++)
8 {
9 scanf("%d",&n);
10 array[499]=1;
11 if(n>1)
12 {
13 printf("*");
14 for(count1=2;count1<=n;count++)
15 {
16 carry=0;
17 for(i=0;i<n;i++)
18 {
19 array[499-i]=(array[499-i]*count1)+carry;
20 if(array[499-i]>9)
21 {
22 carry=array[499-i]/10;
23 array[499-i]=array[499-i]%10;
24 if(count1==n)
25 k++;
26 }
27 else if(array[499-i]<=9)
28 {
29 carry=0;
30 if(count1==n)
31 k++;
32 }
33 }
34 }
35 }
36 if(n==1)
37 k=1;
38 for(p=500-k;p<500;p++)
39 // for(p=475;p<500;p++)
40 printf("*%d",array[500-k]);
printf("*");
42 }
43 return 0;
44 }