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

java写的大数算法

2008-04-27 22:19 351 查看
用例子阐述:
例题:

nPOJ 1503 Integer Inquiry

–Description
省略

–Input
The input will consist of at most 100 lines of text, each of which contains a single VeryLongInteger. Each VeryLongInteger will be 100 or fewer characters in length, and will only contain digits (no VeryLongInteger will be negative).

The final input line will contain a single zero on a line by itself.

–Output
Your program should output the sum of the VeryLongIntegers given in the input.
–Sample Input

•123456789012345678901234567890
•123456789012345678901234567890
•123456789012345678901234567890
•0
–Sample Output

•370370367037037036703703703670

题解:

import java.io.*;
import java.util.*;
import java.math.BigInteger;
public class Main {
public static void main(String[] args){
BigInteger sum=new BigInteger("0");
BigInteger num;
Scanner cin=new Scanner(System.in);
for(;;)
{
num=cin.nextBigInteger();
if(num.toString()=="0")break;
sum=sum.add(num);
}
System.out.println(sum.toString());
}
}

补方法如下:

add
public BigInteger add(BigInteger val) throws ArithmeticException


返回一个 BigInteger ,其值是 (this + val) 。

subtract
public BigInteger subtract(BigInteger val)


返回一个 BigInteger ,其值是 (this - val) 。

multiply
public BigInteger multiply(BigInteger val)


返回一个 BigInteger ,其值是 (this * val) 。

divide
public BigInteger divide(BigInteger val) throws ArithmeticException


返回一个 BigInteger ,其值是 (this / val) 。 如果 val == 0 ,则抛出 ArithmeticException 。

remainder
public BigInteger remainder(BigInteger val) throws ArithmeticException


返回一个 BigInteger ,其值是 (this % val) 。 如果 val == 0,则抛出 ArithmeticException 。

hobo 2008-04-27 22:19 发表评论
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: