Bull Math
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 14488 | Accepted: 7445 |
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.
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
就是模拟乘法运算
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
using namespace std;
int sum[4000];
int a[2000], b[2000];
int Max;
void BigNum(char ca[], char cb[])
{
int i, j;
int len_ca = strlen(ca);
int len_cb = strlen(cb);
for ( i = 0;i < len_ca; i++ )
{
for ( j = 0;j < len_cb; j++ )
{
sum[i+j] = sum[i+j]+a[i]*b[j];
}
}
int carry = 0;
for ( i = 0;i <= Max; i++ )
{
int t = sum[i]+carry;
sum[i] = t%10;
carry = t/10;
}
}
void init(char ca[], char cb[])
{
int i;
memset(sum, 0, sizeof(sum));
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
int len_ca = strlen(ca);
int len_cb = strlen(cb);
Max = max(len_ca, len_cb)*2;
for ( i = 0;i < len_ca; i++ )
{
a[i] = ca[len_ca-i-1]-'0';
}
for ( i = 0;i < len_cb; i++ )
{
b[i] = cb[len_cb-i-1]-'0';
}
}
int main()
{
char ca[2000];
char cb[2000];
int i;
scanf ( "%s %s", ca, cb );
init(ca, cb);
// for ( i = 0;i < 4; i++ )
// {
// printf ( "%d ", a[i] );
// printf ( "%d ", b[i] );
// }
BigNum(ca, cb);
for ( i = Max; i > 0; i-- )
{
if (sum [i] != 0)
break;
}
for ( i; i >=0; i-- )
{
printf ( "%d", sum[i] );
}
printf ( "\n" );
}
代码菜鸟,如有错误,请多包涵!!!
如果有帮助记得鼓励我一下,谢谢!!!