java写的大数算法
用例子阐述:
例题:
题解:
补方法如下:
add
![](http://www.cnitblog.com/weiweibbs/aggbug/42846.html)
例题:
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.
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.
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) 。
public BigInteger subtract(BigInteger val)
- 返回一个 BigInteger ,其值是 (this - val) 。
public BigInteger multiply(BigInteger val)
- 返回一个 BigInteger ,其值是 (this * val) 。
public BigInteger divide(BigInteger val) throws ArithmeticException
- 返回一个 BigInteger ,其值是 (this / val) 。 如果 val == 0 ,则抛出 ArithmeticException 。
public BigInteger remainder(BigInteger val) throws ArithmeticException
- 返回一个 BigInteger ,其值是 (this % val) 。 如果 val == 0,则抛出 ArithmeticException 。