天天看點

java.math.BigIntegerBigInteger定義BigInteger常用方法程式執行個體

BigInteger定義

        public class BigInteger extends Number implementsComparable<BigInteger>

        不可變的任意精度的整數。所有操作中,都以二進制補碼形式表示BigInteger(如Java的基本整數類型)。BigInteger提供所有Java的基本整數操作符的對應物,并提供java.lang.Math的所有相關方法。另外,BigInteger還提供以下運算:模算術、GCD計算、質數測試、素數生成、位操作以及一些其他操作。

        算術運算的語義完全模仿Java整數算術運算符的語義,如TheJava Language Specification 中所定義的。例如,以零作為除數的除法抛出ArithmeticException,而負數除以正數的除法則産生一個負(或零)的餘數。Spec中關于溢出的細節都被忽略了,因為BigIntegers所設定的實際大小能适應操作結果的需要。

        位移操作的語義擴充了Java的位移操作符的語義以允許産生負位移距離。帶有負位移距離的右移操作會導緻左移操作,反之亦然。忽略無符号的右位移運算符(>>>),因為該操作與由此類提供的“無窮大的詞大小”抽象結合使用時毫無意義。

        逐位邏輯運算的語義完全模仿Java的逐位整數運算符的語義。在執行操作之前,二進制運算符(and、or、xor)對兩個操作數中的較短操作數隐式執行符号擴充。

        比較操作執行有符号的整數比較,類似于Java的關系運算符和相等性運算符執行的比較。提供的模算術操作用來計算餘數、求幂和乘法可逆元。這些方法始終傳回非負結果,範圍在 0 和 (modulus - 1)(包括)之間。

        位操作對其操作數的二進制補碼表示形式的單個位進行操作。如有必要,操作數會通過擴充符号來包含指定的位。單一位操作不能産生與正在被操作的BigInteger符号不同的BigInteger,因為它們僅僅影響單個位,并且此類提供的“無窮大詞大小”抽象可保證在每個BigInteger前存在無窮多的“虛拟符号位”數。

        當為任何輸入參數傳遞 null對象引用時,此類中的所有方法和構造方法都将抛出 NullPointerException。

BigInteger常用方法

        BigInteger不是基本資料類型之一,它其實更像String,是Java裡的一個類,然而它的初始化方式卻沒有String那麼友善可以直接指派,而是跟其他自定義的類一樣,要調用它的構造器進行初始化。這個類的取值範圍原則上是沒有上限的,取決于你的計算機的記憶體,它的構造器有以下幾種:

        1、BigInteger(byte[] val):将包含BigInteger的二進制補碼表示形式的byte數組轉換為 BigInteger。

        2、BigInteger(int signum, byte[] magnitude):将BigInteger的符号-數量表示形式轉換為BigInteger。

        3、BigInteger(int bitLength, int certainty, Random rnd):構造一個随機生成的正BigInteger,它可能是一個具有指定bitLength的素數。

        4、BigInteger(int numBits, Random rnd):構造一個随機生成的BigInteger,它是在0到(2^numBits -1)(包括)範圍内均勻分布的值。

        5、BigInteger(String val):将BigInteger的十進制字元串表示形式轉換為BigInteger。

        6、BigInteger(String val, int radix):将指定基數的BigInteger的字元串表示形式轉換為BigInteger。

        并且在Biginteger類中還預定義了三個常量字段,分别是:staticBigInteger ONE: BigInteger的常量 1。static BigInteger TEN:BigInteger的常量10。static BigInteger ZERO:BigInteger的常量 0。

        大數的加減乘除也不能使用+、-、*、/這些運算符号,BigInteger類沒有對這些運算符号進行重定義,取而代之的是用一些方法來代替,比如add()、subtract()、mutiply()、divide()這四種方法。下面列舉了BigInteger類中的常用方法。

        BigInteger abs() 傳回大整數的絕對值

        BigInteger add(BigInteger val)傳回兩個大整數的和

        BigInteger and(BigInteger val) 傳回兩個大整數的按位與的結果

        BigInteger andNot(BigInteger val) 傳回兩個大整數與非的結果

        BigInteger divide(BigInteger val) 傳回兩個大整數的商

        double doubleValue()   傳回大整數的double類型的值

        float floatValue()   傳回大整數的float類型的值

        BigInteger gcd(BigInteger val) 傳回大整數的最大公約數

        int intValue() 傳回大整數的整型值

        long longValue() 傳回大整數的long型值

        BigInteger max(BigInteger val)傳回兩個大整數的最大者

        BigInteger min(BigInteger val)傳回兩個大整數的最小者

        BigInteger mod(BigInteger val)用目前大整數對val求模

        BigInteger multiply(BigInteger val)傳回兩個大整數的積

        BigInteger negate() 傳回目前大整數的相反數

        BigInteger not() 傳回目前大整數的非

        BigInteger or(BigInteger val) 傳回兩個大整數的按位或

        BigInteger pow(int exponent)傳回目前大整數的exponent次方

        BigInteger remainder(BigInteger val) 傳回目前大整數除以val的餘數

        BigInteger leftShift(int n) 将目前大整數左移n位後傳回

        BigInteger rightShift(int n) 将目前大整數右移n位後傳回

        BigInteger subtract(BigInteger val)傳回兩個大整數相減的結果

        byte[] toByteArray(BigInteger val)将大整數轉換成二進制反碼儲存在byte數組中

        String toString()将目前大整數轉換成十進制的字元串形式

        BigInteger xor(BigInteger val) 傳回兩個大整數的異或

        int compareTo(BigInteger val)将此 BigInteger與指定的 BigInteger進行比較。小于則傳回-1,等于則傳回0,大于則傳回1

        boolean equals(Object x)比較此 BigInteger與指定的 Object的相等性。

        static BigInteger valueOf(long val)傳回其值等于指定 long的值的 BigInteger。

        int hashCode() 傳回此 BigInteger 的哈希碼。

程式執行個體

package com.zxt.test2;
 
import java.math.BigInteger;
 
/**
 * 水仙花數(Narcissistic number):也被稱為超完全數字不變數(pluperfect digital invariant,
 * PPDI)、自戀數、自幂數等
 *
 * 水仙花數是指一個 n 位數(n≥3 ),它的每個位上的數字的 n 次幂之和等于它本身(例如:1^3 + 5^3+ 3^3 = 153)。
 *
 * 21位水仙花數
 */
 
// 小資料規模時,可以直接根據定義求解,當資料變大時,則使用BigInteger來求解
public classNarcissistic {
 
    // 指定需要求解的位數
    private static int size = 7;
    // 用一個BigInteger數組來存儲0-9的size次方的值
    private static BigInteger[] base = new BigInteger[10];
 
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();// 程式開始時間
 
        for (int i = 0; i < base.length; i++) {
            base[i] = calcu(i, size);
        }
 
        // 每個數字出現幾次(那就是0-9出現的次數與0-9的size次方的乘積之和與原數比較,若相等那就是水仙花數)
        int[] usedTimes = new int[10];
        BigIntegerk = BigInteger.TEN.pow(size - 1);
        // compareTo方法來比較,小于則傳回-1,等于則傳回0,大于則傳回1
        while (k.compareTo(BigInteger.TEN.pow(size)) == -1) {
            getUsedTimes(usedTimes, k);
            test(usedTimes, base, k);
 
            k = k.add(BigInteger.ONE);
        }
 
        long endTime = System.currentTimeMillis();// 程式結束時間
        System.out.println((endTime - startTime) / 1000f + "秒"); // 運作總時
    }
 
    // 統計BigInteger中0-9數字出現的次數
    private static void getUsedTimes(int[] usedTimes, BigInteger num) {
        Stringstr = num.toString();
 
        for (int i = 0; i < usedTimes.length; i++) {
            usedTimes[i] = 0;
        }
 
        for (int i = 0; i < str.length(); i++) {
            usedTimes[str.charAt(i) - '0']++;
        }
    }
 
    // 根據統計得到的次數,判斷該BigInteger是否是一個水仙花數
    private static void test(int[] usedTimes, BigInteger[] base, BigInteger num) {
        BigIntegerbn = BigInteger.ZERO;
 
        for (int i = 0; i < usedTimes.length; i++) {
            bn = bn.add(base[i].multiply(BigInteger.valueOf(usedTimes[i])));
        }
 
        // BigInteger判斷相等可以使用compareTo或者equals方法(equals方法傳回布爾值)
        if (bn.equals(num)) {
            System.out.println(num);
        }
    }
 
    // 計算某數的size次方(用BigInteger存儲)
    private static BigInteger calcu(int num, int size) {
 
        // BigInteger res = BigInteger.ONE;
        // for (int i = 0; i < size; i++) {
        // BigInteger.valueOf(long val):傳回其值等于指定 long 的值的 BigInteger。
        // res = res.multiply(BigInteger.valueOf(num));
        // }
 
        // return res;
 
        // BigInteger pow(int exponent):傳回其值為 (this^exponent) 的 BigInteger。
        return BigInteger.valueOf(num).pow(size);
    }
}