#include <stdio.h>
#define SIZE 1001
#define BASE 10
int add(int *c,int *d,int* e); //adds arrays c and d into e
int add1(int x, int y,int* z); //adds digits of the arrays
int multiply(int *f,int multiple,int* g); //multiplies f by multiple into g
int main()
{
int a[SIZE],b[SIZE],test=0,i;
for(i=0;i<SIZE;i++)//initialize a & b to 0
{
a[i]=0;
b[i]=0;
}
a[1000]=9;
a[999]=1; //a=19
int n=3; //only works where n<=2
multiply(a,n,B)/>; //b=n*a btw b is not capitalized in my code
for(i=0;i<SIZE;i++) //prints b
{ /* /removes leading zero's */
if(test==0 && b[i]==0) continue; // ie 1 instead of 00000001
test=1;
printf("%d",b [i]);
}
if(!test)printf("0");
return 0;
}
int add1(int x,int y,int* z) //adds digits - and takes care of the carry into z
{
int p;
p=z[x]+y;
if(p<BASE) //this recursively tests whether there is a carry
{
z[x]+=y;
return 0;
}
else
{
add1(x-1,p/BASE,z); //carry
z[x]=(p%BASE);
return 0;
}
}
int add(int *c,int *d,int* e) //adds two arrays c and dtogether into and puts answer into array e
{
int i,sum;
for(i=SIZE-1;i>=0;i--)
{
sum=c[i]+d[i];
if(e[i]+sum<BASE) //no carry if true
{
e[i]+=sum;
}
else
{
add1(i,sum,e); //adds the digits and takes care of the carry
}
}
return 0;
}
int multiply(int *f,int multiple, int* g) // times array f by multiple - into array g
{ // using 5*a = a+a+a+a+a
int i;
if(multiple==2)
{
add(f,f,g);
return 0;
}
else
for(i=0;i<multiple;i++)
{
add(f,g,g); //g+=f ??
}
return 0;
}
This post has been edited by simeesta: 03 May 2010 - 10:46 AM

New Topic/Question
Reply




MultiQuote





|