Bull Math
Description
Bulls are so much better at math than the cows. They can multiply huge integers together and get perfectly precise answers ... or so they say. Farmer John wonders if their answers are correct. Help him check the bulls' answers. Read in two positive integers (no more than 40 digits each) and compute their product. Output it as a normal number (with no extra leading zeros).
FJ asks that you do this yourself; don't use a special library function for the multiplication. Input
* Lines 1..2: Each line contains a single decimal number.
Output
* Line 1: The exact product of the two input lines
Sample Input 11111111111111 1111111111 Sample Output 12345679011110987654321 Source |
[Submit] [Go Back] [Status] [Discuss]
解析:假设用字符数组读入两个超长数a、b,用int c[] 数组记录他们的乘积。
len_a表示字符数组 a 的长度,a[len_a-i]表示字符数组 a 所代表数字从个位往高位方向的第几位,如:a[len_a-1]代表数字a的个位,a[len_a-2]代表数字a的十位,等等。b数组相关定义与此类似。
c[k]表示数字c从个位往高位方向的第几位,比如c[1]代表数字c的个位,c[2]代表数字c的十位,等等。
c[k]=∑(a[len_a-i]-'0')*(b[len_b-(k+1-i)]-'0') (i=1——>len_a ,1<=k+1-i<=len_b);
代码:
#include<cstdio>
#include<cstring>
#define maxn 250
using namespace std;
char a[maxn+50],b[maxn+50];
int c[maxn*maxn+100];
void redirect()
{
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
}
void work()
{
int i,j,k,last=0,len1=strlen(a),len2=strlen(b);
c[0]=len1+len2-1;
for(k=1;k<=c[0];k++)
{
c[k]=last;
for(i=1;i<=len1;i++)
if(k+1-i>=1 && k+1-i<=len2)
c[k]+=(a[len1-i]-'0')*(b[len2-(k+1-i)]-'0');
last=c[k]/10,c[k]%=10;
}
if(last>0)printf("%d",last);
for(k=c[0];k>=1;k--)printf("%d",c[k]);
printf("\n");
}
int main()
{
redirect();
while(gets(a)!=NULL)
gets(b),work();
return 0;
}