A lot of time we have tried to work with large numbers in c and end up getting a round off or a zero. This is just on of the many ways to work with large numbers without any external library support. We have implemented our code and storage with the help of the derived data type : array.
The logic is pretty simple. We implement a mathematical multiplication the way we would have multiplied on paper and pen. So starting with the last index in thte array we multiply the array elements and carry and place digits accordingly.
ALGORITHM ::
- 1.start
- 2.read a number
- 3.if (a=0) <= number goto 4 else goto 10
- 4.if carry<>0 AND place <>0 goto 5 else goto 9
- 5.mul=array[index]*a
- 6.sum=mul+carry
- 7.’place’ the unity place digit and ‘carry’ the rest
- 8.index=index+1
- 9.a=a+1
- write array
- end
The code would include calculating of indexes for optimization of time. It goes like this :
//code to find factorials of numbers greater than fundamental data type
/*================================================*/
/*
mark ::marks the index after eliminating 0's from resultant array
carry ::carries the value o be placed at the next index
sum ::sums the product and carry value
place ::places the value at index
index ::index to work with
mul ::multiplies the number with array index
a ::loop variable for numbers
arr[] ::array for factorial
num ::number to find factorial
lastindex ::stores index of the digit from where the factorial exists
Example::for 00000720, 6 is the last index
loop ::loop variable to check index from where the factorial starts existing
By ::CHINMOY KANJILAL
*/
/*================================================*/
#include<stdio.h>
#include<conio.h>
#define MAX 2000
int main()
{
int mark,carry,sum=0,place,index,mul,a,arr[MAX]={0},num,lastindex=1,loop;
printf("Enter number");
scanf("%d",&num);
arr[0]=1;
for(a=2;a<=num;a++)
{
index=0; //initialize index to 0 for each number,(start multiplying from the beginning)
carry=1; //initialize carry to 1 to enter loop only
place=1; //initialize place to 1 to enter loop only
while((carry!=0 || place!=0) || index<lastindex) //at any end position carry and sum will be 0, also there can be 2 consecutive 0's. So check for number of digits in the factorial
{
for(loop=0;loop<MAX-1;loop++)
{
if(arr[loop]==0 && arr[loop+1]!=0)
{
lastindex=a; //number of digits
}
}
if(index==0)
{
carry=0;
}
mul=a*arr[index]; //mutiply each element
sum=mul+carry; //add carry to multiplied
carry=sum/10; //next carry will be %10
place=sum%10; //current place value is /10
arr[index]=place; //place value
index++; //next index
printf("For %d at index %d::Carry %d Place %dn",a,index,carry,place); //processing visual
}
}
for(a=0;a<MAX;a++)
{
if(arr[a+1]==0 && arr[a]!=0)
{
mark=a; //check for non existance of filler 0's
}
}
printf("n");
for(a=mark;a>=0;a--)
{
printf("%d",arr[a]);
}
printf("n");
getch();
return 0;
}
[The executable can be tested here : factorial]
