int
通过
BigInteger
您应该做一些更改,但是,我更改了您的代码,并提出了如下内容:
public static BigInteger FibonacciB(int n) {
final BigInteger one = BigInteger.ONE;
final BigInteger zero = BigInteger.ZERO;
final BigInteger two = new BigInteger(String.valueOf(2));
final BigInteger minusOne = one.negate();
BigInteger num = new BigInteger(String.valueOf(n));
if (num.equals(zero)) {
return zero;
} else if (num.compareTo(two) <= 0) {
return one;
}
BigInteger[][] number = {{one, one}, {one, zero}};
BigInteger[][] result = {{one, one}, {one, zero}};
while (num.compareTo(zero) > 0) {
if (num.mod(two).equals(one)) result = MultiplyMatrixB(result, number);
number = MultiplyMatrixB(number, number);
num = num.divide(two);
}
if (num.compareTo(zero) < 0)
return result[1][1].multiply(minusOne);
return result[1][1];
}
//矩阵多乘子方法:
public static BigInteger[][] MultiplyMatrixB(BigInteger[][] mat1, BigInteger[][] mat2) {
return new BigInteger[][]{
{(mat1[0][0].multiply(mat2[0][0])).add((mat1[0][1].multiply(mat2[1][0]))),
(mat1[0][0].multiply(mat2[0][1])).add((mat1[0][1].multiply(mat2[1][1])))
},
{
(mat1[1][0].multiply(mat2[0][0])).add((mat1[1][1].multiply(mat2[1][0]))),
(mat1[1][0].multiply(mat2[0][1])).add((mat1[1][1].multiply(mat2[1][1])))
}
};
}