题目链接:http://acm.sdibt.edu.cn:8080/judge/contest/view.action?cid=396#problem/B

觉得从这道题可以得到大数乘法的一个模板,代码如下,旨在交流:

#include <stdio.h>
#include <string.h>
#include <malloc.h>
char word1[10000],word2[10000];
void product()
{
	int n1=strlen(word1),n2=strlen(word2);
	int *p,i,j;
	p=(int *)malloc(sizeof(int)*(n1+n2+100));//存储结果
	for(i=0;i<n1+n2;i++)//初始化数组
		p[i]=0;
	p[n1+n2]=1;
	for(i=0;i<n1;i++)
		for(j=0;j<n2;j++)
                    p[i+j+1]+=(word1[i]-48)*(word2[j]-48);
	for(i=n1+n2-1;i>=0;i--)//进位
	if(p[i]>=10)
	{
		  p[i-1]+=p[i]/10;
		  p[i]%=10;
	}
	i=0;
	while(p[i]==0)
		 i++;
	if(i==n1+n2)
		 printf("0");
	else
	{
	    for(;i<n1+n2;i++)
		    printf("%d",p[i]);
	}
	  printf("\n");
}
int main()
{
       memset(word1,0,sizeof(word1));
       while(gets(word1)!=NULL)
       {  
	   memset(word2,0,sizeof(word2));
	   gets(word2);
	   product();
	   memset(word1,0,sizeof(word2));
       }
       return 0;
}

发表评论

电子邮件地址不会被公开。

Post Navigation