Bull Math
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 16580 | Accepted: 8451 |
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
过程不懂的话,看这篇文章
https://blog.csdn.net/qq_41325698/article/details/88929961
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define range 103
void multi(char a[],char b[],char s[])
{
int i,j,k=0,alen=strlen(a),blen=strlen(b),sum=0,res[range][range]={0},flag=0;
char result[range];
for(i=0;i<alen;i++)
for(j=0;j<blen;j++)
res[i][j]=(a[i]-'0')*(b[j]-'0');
// 模拟乘法
for(i=alen-1;i>=0;i--)
{
for(j=blen-1;j>=0;j--)
sum+=res[i+blen-1-j][j];
result[k]=sum%10;
k++;
sum/=10;
}
for(i=blen-2;i>=0;i--)
{
for(j=0;j<=i;j++)
sum+=res[i-j][j];
result[k]=sum%10;
k++;
sum/=10;
}
// 处理最后的进位
if(sum)
{
result[k]=sum;
k++;
}
for(i=0;i<k;i++)
result[i]+='0';
// 字符串翻转
for(i=k-1;i>=0;i--)
s[i]=result[k-1-i];
s[k]='\0';
printf("%s\n",s);
}
int main()
{
char a[range],b[range],res[range];
cin>>a>>b;
multi(a,b,res);
return 0;
}