I was trying to solve the problem JULKA given on SPOJ
in the code i have assumed
1.number is the total number of apples
2.more is how many more apples Klaudia has than Natalia.
3.x is the number of apples with Klaudia
4.y is the number of apples with natalia.
my code works for the inputs
10
2
3232
1233
giving the outputs
6
4
2232
999
but fails for the input
999
1
giving the output
500
49
it should have given 499 instead of 49. i am posting my code plz suggest me a correct algorithm for subtraction
#include<stdio.h>
#include<string.h>
int main()
{
char x[103],y[103],number[103],more[103];
int t=10,ln,lm,lx,i,j,carry,k,l;
while(t--)
{
for(i=0;i<=102;i++)
{x[i]='\0';y[i]='\0';}
carry=0;
scanf("%s",number);
scanf("%s",more);
ln=strlen(number);
lm=strlen(more);
//Adding 0 at the beginning to make length of more = lengthe of number
while(lm!=0)
{
more[ln-1]=more[lm-1];
ln--;
lm--;
}
for(i=0;i<ln;i++)
more[i]='0';
ln=strlen(number);
//Calculation of x
for(i=ln-1;i>=0;i--)
{
k=carry + (int)number[i]+(int)more[i]-96;
x[i]=(int)k%10+48;
carry=k/10;
}
l=ln;
if(carry!=0)
{
while(l!=0)
{
x[l]=x[l-1];
l--;
}
x[0]=carry+48;
}
k=((int)x[0]-48)%2;
for(i=1;i<ln;i++)
{
k=k*10;
l=(int)x[i]-48 + k;
x[i]=l/2 + 48;
k=l%2;
}
x[0]=((int)x[0]-48)/2 + 48;
ln=strlen(number);
//PRINTING x
i=0;
while(x[i]=='0')i++;
if(strlen(x)==i)
printf("0");
else
for(l=i;l<=ln;l++)
printf("%c",x[l]);
printf("\n");
//SUBTRACTION
for(i=ln-1;i>=0;i--)
{
if(x[i]>=more[i])
{
y[i]=(int)((int)x[i]-(int)more[i])+48;
}
else
{
x[i-1]=(int)((int)x[i-1]-1);
l=(int)((int)x[i]+10-(int)more[i]);
y[i]=l+48;
}
}
//PRINTING y
i=0;
while(y[i]=='0')i++;
if(strlen(y)==i)
printf("0");
else
for(l=i;l<=ln;l++)
printf("%c",y[l]);
printf("\n");
}
return 0;
}