大數的相關操作
創建大數
BigInteger a=new BigInteger("123456");//參數一定要是字符串
BigInteger a=BigInteger.valueOf(123);//參數可以是int或long,不能是小數
大數賦值
BigInteger a=in.nextBigInteger();
大數運算
a.add(b);//加
a.subtract(b);//減
a.divide(b);//除
a.multiply(b);//乘
大數比較
a.equals(b);//如果a、b相等返回true否則返回false
a.compareTo(b);//a小於b返回-1,等於返回0,大於返回1
常用方法(返回值也是大整型)
a.mod(b);//求餘,除數不能是負數。無論被除數是不是正數,結果都是正數
a.remainder(b);//求餘,除數可以負數。兩個操作數只要有一個是負數,結果即爲負數
a.gcd(b);//求最大公約數
a.max(b);//求最大值
a.min(b);//求最小值
BigInteger中的常數
BigInteger.ZERO//大整數0
BigInteger.ONE//大整數1
BigInteger.TEN//大整數10
例題學習(杭電1002):
代碼實現:
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int t=1;
while(n-->0){
BigInteger a = sc.nextBigInteger();
BigInteger b = sc.nextBigInteger();
BigInteger c = a.add(b);
System.out.println("Case "+t+":");
System.out.println(a+" + "+b+" = "+c);
if(n!=0) {
System.out.println();
}
t++;
}
}
}
例題學習(杭電1042):
代碼實現:
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
int n =sc.nextInt();
BigInteger sum=BigInteger.ONE;
for (int i = 1; i <=n ; i++) {
sum=(sum.multiply(BigInteger.valueOf(i)));
}
System.out.println(sum);
}
}
}