poj 2389 解题报告 大数乘法

题目:

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.

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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值