大数乘法(模版)

直接上代码:

#include<stdio.h>
#include<string.h>
int main()
{
	int ncases,i,j,alen,blen,sum[1001];
	char a[1001],b[1001],ans[1001];
	scanf("%d",&ncases);
	while(ncases--)
	{
		memset(a,0,sizeof(a));
		memset(b,0,sizeof(b));
		memset(sum,0,sizeof(sum));
		memset(ans,0,sizeof(ans));
		scanf("%s %s",a,b);
		alen=strlen(a);
		blen=strlen(b);
		if(a[0]=='0'||b[0]=='0')
		{
			printf("0\n");
			continue;;
		}
		for(i=0;i<=alen+blen-1;i++)
		{
			sum[i]=0;
		}
		for(i=0;i<=alen-1;i++)
		{
			for(j=0;j<=blen-1;j++)
			{
				sum[i+j+1]=sum[i+j+1]+(a[i]-'0')*(b[j]-'0');/*乘法*/
			}
		}
		for(i=alen+blen-1;i>=0;i--)
		{
			if(sum[i]>=10)
			{
				sum[i-1]=sum[i-1]+sum[i]/10;
				sum[i]=sum[i]%10;/*进位*/
			}
		}
		i=0;
		while(sum[i]==0)
		{
			i++;
		}
		for(j=0;i<=alen+blen-1;i++,j++)
		{
			ans[j]=sum[i]+'0';
		}
		ans[j]='\0';
		printf("%s\n",ans);
	}
	return 0;
}






你可能感兴趣的:(大数乘法(模版))