在程序設計競賽中會遇到高精度運算的問題,C++沒有高精度運算,只能手動模擬人工運算,手動實現高精度,而 java.math
包中的 BigInteger
提供了高精度的基本運算,所以競賽中經常使用 Java 解決高精度運算問題。java
固然若是比賽支持 python
就當我沒說。python
BigInteger 類在 java.math.BigInteger 包中,首先引用該包。數組
import java.math.BigInteger;
BigInteger 對象的建立ide
BigInteger a = new BigInteger("123"); // 這裏是字符串
改變 BigInteger 的值函數
String str = "123"; BigInteger a = BigInteger.valueOf(str); int num = 456; BigInteger a = BigInteger.valueOf(num);
基本常量spa
a = BigInteger.ONE // 1 b = BigInteger.TEN // 10 c = BigInteger.ZERO // 0
直接讀入 BigInteger設計
Scanner in = new Scanner(System.in); while(in.hasNext()) //等同於!=EOF { BigInteger a; a = in.nextBigInteger(); System.out.print(a.toString()); }
間接讀入 BigIntegercode
Scanner in = new Scanner(System.in); while(in.hasNext()) //等同於!=EOF { String s = in.nextLine(); BigInteger a = new BigInteger(s); System.out.print(a.toString()); }
BigInteger 直接輸出對象
System.out.print(a);
BigInteger 轉化成十進制表示的 Stringip
System.out.print(a.toString());
BigInteger 轉化成 p 進製表示的 String
int p = 2; System.out.print(a.toString(p)); // 輸出a的二進制
BigInteger 二進制下的長度
BigInteger n = new BigInteger("12"); System.out.println(n.bitLength()); // 4
BigInteger 之間的比較
BigInteger a = new BigInteger("123"); BigInteger b = new BigInteger("456"); System.out.println(a.equals(b)); // a == b 時爲 true 不然爲 false
BigInteger a = new BigInteger("123"); BigInteger b = new BigInteger("456"); if(a.compareTo(b) == 0) System.out.println("a == b"); // a == b else if(a.compareTo(b) > 0) System.out.println("a > b"); // a > b else if(a.compareTo(b) < 0) System.out.println("a < b"); // a < b
加法
BigInteger a = new BigInteger("123"); BigInteger b = new BigInteger("456"); a.add(b);
減法
BigInteger a = new BigInteger("123"); BigInteger b = new BigInteger("456"); a.subtract(b);
乘法
BigInteger a = new BigInteger("123"); BigInteger b = new BigInteger("456"); a.multiply(b);
除法
BigInteger a = new BigInteger("123"); BigInteger b = new BigInteger("456"); a.divide(b);
取餘
BigInteger a = new BigInteger("123"); BigInteger b = new BigInteger("456"); BigInteger c = b.remainder(a); System.out.println(c);
除法取餘
BigInteger a = new BigInteger("123"); BigInteger b = new BigInteger("456"); BigInteger result[] = b.divideAndRemainder(a); // 該函數返回的是數組 System.out.println("商是:" + result[0] + ";餘數是:" + result[1]);
最大公約數
BigInteger a = new BigInteger("12"); BigInteger b = new BigInteger("56"); System.out.println(a.gcd(b)); // 4
絕對值
BigInteger a = new BigInteger("-12"); System.out.println(a.abs()); // 12
取反數
BigInteger a = new BigInteger("-12"); System.out.println(a.negate()); // 12
冪
BigInteger a = new BigInteger("2"); System.out.println(a.pow(3)); // 8