hdu1402 大数A*B
问题来源:
http://acm.hdu.edu.cn/showproblem.php?pid=1402
题目描述:
Calculate A * B.
Input
Each line will contain two integers A and B. Process toend of file.
Note: the length of each integer will not exceed 50000.
Output
For each case, output A * B in one line.
Sample Input
1
2
1000
2
Sample Output
2
2000
计算a*b,6位一乘,否则tle,而且只能交G++,另外傅里叶算法也可以
程序代码:
#include<stdio.h>
#include<string.h>
#define N 50100
int a[N],b[N];
long long A[N],B[N],ans[N];
char s1[N],s2[N];
int main()
{
int i,j,len1,len2,l,r,L,R,x;
long long t,p,c;
while(scanf("%s%s",s1,s2)!=EOF)
{
if(s1[0]=='0'||s2[0]=='0')
{
printf("0\n");
continue;
}
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(A,0,sizeof(A));
memset(B,0,sizeof(B));
memset(ans,0,sizeof(ans));
len1=strlen(s1);
len2=strlen(s2);
l=len1-1;
r=len2-1;
for(i=0;i<len1;i++)
a[l--]=(s1[i]-'0');
for(j=0;j<len2;j++)
b[r--]=(s2[j]-'0');
L=0;R=0;
for(i=0;i<len1;i+=6)
A[L++]=a[i+5]*100000+a[i+4]*10000+a[i+3]*1000+a[i+2]*100+a[i+1]*10+a[i];
for(i=0; i<len2; i+=6)
B[R++]=b[i+5]*100000+b[i+4]*10000+b[i+3]*1000+b[i+2]*100+b[i+1]*10+b[i];
for(i=0;i<L;i++)
{
c=0;
for(j=0; j<R; j++)
{
t=A[i]*B[j]+ans[i+j]+c;
ans[i+j]=t%1000000;
c=t/1000000;
}
if(c)
ans[i+j]=c;
}
for(x=L+R;ans[x]==0;x--){
}
printf("%lld",ans[x]);
for(x--; x>=0;x--)
printf("%06lld",ans[x]);
printf("\n");
}
return 0;
}