题目:
Bull Math
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 14630 | Accepted: 7514 |
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
代码:
1.Java大数很简洁,但时空复杂度较高
import java.math.BigInteger;
import java.util.Scanner;
public class Main { //3000k 1500ms
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
BigInteger a = sc.nextBigInteger();
BigInteger b = sc.nextBigInteger();
System.out.println(a.multiply(b));
}
}
}
2.基础的模拟算法
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
char a[45],b[45];
int c[45],d[45],e[85];
/*
思想:模拟乘法手算过程
*/
int main(){ // 700k 16ms
while(~scanf("%s%s",&a,&b)){
int la=strlen(a),lb=strlen(b);
//由于数组从前向后是由低到高,与熟悉的数字存储方式相反,因此存入int数组中时可以逆序存储
for(int i=0,j=la-1;i<la;++i,--j){
c[i]=a[j]-'0';
}
for(int i=0,j=lb-1;i<lb;++i,--j){
d[i]=b[j]-'0';
}
memset(e,0,sizeof(e));
for(int i=0;i<la;++i){
for(int j=0;j<lb;++j){
e[i+j]+=c[i]*d[j];
}
}
for(int i=0;i<la+lb;++i){
if(e[i]>=10){
e[i+1]+=e[i]/10;
e[i]%=10;
}
}
if(e[la+lb-1]) printf("%d",e[la+lb-1]);//m位的整数和n位的整数相乘,结果为m+n或m+n-1位
for(int i=la+lb-2;i>=0;--i){
printf("%d",e[i]);
}
puts("");
}
return 0;
}
3.稍作改进,代码更简洁一些
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
char a[45],b[45];
int e[85];
int main(){ // 690k 16ms
while(~scanf("%s%s",&a,&b)){
int la=strlen(a),lb=strlen(b);
memset(e,0,sizeof(e));
for(int i=0;i<la;++i){
for(int j=0;j<lb;++j){
e[la-1-i+lb-1-j]+=(a[i]-'0')*(b[j]-'0');
}
}
for(int i=0;i<la+lb;++i){
if(e[i]>=10){
e[i+1]+=e[i]/10;
e[i]%=10;
}
}
if(e[la+lb-1]) printf("%d",e[la+lb-1]);
for(int i=la+lb-2;i>=0;--i){
printf("%d",e[i]);
}
puts("");
}
return 0;
}