您的位置:首页 > 编程语言 > Java开发

POJ 2389 Bull Math(大数乘法,还是Java好)

2016-05-14 00:44 531 查看
Bull Math

Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 14252Accepted: 7350
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

USACO 2004 November

原题链接:http://poj.org/problem?id=2389

大数乘法,数据只有一组!

AC代码:

import java.math.BigInteger;
import java.util.Scanner;

public class Main {
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));
}
}

}


AC代码2:

#include <stdio.h>
#include <string.h>
#define MAX 220
int main()
{
char s1[MAX],s2[MAX];
int a1[MAX],a2[MAX],p[2*MAX];;
int i,j,len_1,len_2;
memset(a1,0,sizeof(a1));
memset(a2,0,sizeof(a2));
memset(p,0,sizeof(p));
gets(s1);
gets(s2);
len_1=strlen(s1);
len_2=strlen(s2);
for (j=0,i=len_1-1;i>=0;i--)
{
a1[j++]=s1[i]-'0';
}

for (j=0,i=len_2-1;i>=0;i--)
{
a2[j++]=s2[i]-'0';
}

for (i=0;i<len_1;i++)
{
for (j=0;j<len_2;j++)
{
p[i+j]+=a1[i]*a2[j];
}
}
for (i=0;i<MAX*2;i++)
{
if(p[i]>9)
{
p[i+1]+=p[i]/10;
p[i]%=10;
}
}

int start=0;
for (i=MAX*2-1;i>=0;i--)
{
if(start)
{
printf("%d",p[i]);
}
else if(p[i])
{
printf("%d",p[i]);
start=1;
}
}
if(!start)
printf("0");

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: