你所認爲的階乘從不是你認爲的N!解密Java大數相乘,解決超過int,long支持的最大長度的數字存儲問題

通常我們認爲階乘是這樣的:

public class Test{
	public static void main(String[] args){
		System.out.println(fac(60));
	}
	public static int fac(int num){
		if(num <= 2){
			return num;
		}else{
			return num*fac(num-1);
		}
	}
}

或者將int替換成long。
但是,你知道嗎???
60! 等於8320987112741390144276341183223364380754172606361245952449277696409600000000000000。wtf?
alt

那麼解決方法就是:大數相乘
import java.math.BigInteger;
public class Test{
    public static void main(String[] args) {
        Integer a = 60;
        BigInteger  s  =fac(new BigInteger(a.toString()));
        System.out.println(s);
        System.out.println(s.toString());
        System.out.println(s.toString().length());
    }
    public  static BigInteger fac(BigInteger num){
        if (num.compareTo(BigInteger.ONE) == 0){
            return BigInteger.ONE;
        }else {
            return num.multiply(fac(num.subtract(BigInteger.ONE)));
        }
    }
}

BigInteger是Java中的一個類。類的取值範圍沒有上限,取決於計算機內存。
它的構造器有以下幾種;

alt
最常用的就是BigInteger(String val)。
大數的+、-、×、÷是用方法來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) 返回兩個大整數的異或

——BY ASirenHereIs

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章