n≥1的斐波那契数列. 46爪哇 [英] Fibonacci sequence for n > 46 Java
本文介绍了n≥1的斐波那契数列. 46爪哇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码,可为n<提供正确的值; 47.
I have the following code which provides the correct values for n < 47.
public static int fib(int n) {
int nthTerm = 0;
if (n == 2)
nthTerm = 1;
else {
double goldenRatio = (1 + Math.sqrt(5)) / 2;
nthTerm = (int) (Math.round(Math.pow(goldenRatio, n)
- Math.pow(1 - goldenRatio, n)) / Math.sqrt(5));
if (n % 2 == 1 && n < 45)
nthTerm++;
}
return nthTerm;
}
n的任何值> 46都超出int范围.在n> 46的情况下,我该如何适应这种方法?
Any value for n > 46 is out of int range. How could I adapt this approach to work for n > 46?
P.S.我知道BigInteger,但不怎么擅长,所以我也很感谢使用BigInteger的示例.
P.S. I know of BigInteger but am not very adept at it so I would appreciate an example using BigInteger, too.
推荐答案
您可以将其用于将代码转换成BigInteger.
You can use this for transformated code into BigInteger.
package your.pack
import java.math.BigDecimal;
import java.math.BigInteger;
/**
* Created on 3/6/16.
*/
public class Fibonacci {
private static BigDecimal goldenRatio = new BigDecimal((1 + Math.sqrt(5)) / 2);
private static BigDecimal goldenRatioMin1 = goldenRatio.subtract(BigDecimal.ONE);
private static BigDecimal sqrt5 = new BigDecimal(Math.sqrt(5));
private static BigInteger fib(int n) {
BigInteger nthTerm = new BigInteger("0");
if (n == 2)
nthTerm = BigInteger.ONE;
else {
BigDecimal minResult = goldenRatio.pow(n).subtract(goldenRatioMin1.pow(n));
nthTerm = minResult.divide(sqrt5,0).toBigInteger();
if (n % 2 == 1 && n < 45){
nthTerm = nthTerm.add(BigInteger.ONE);
}
}
return nthTerm;
}
private static int fib2(int n) {
int nthTerm = 0;
if (n == 2)
nthTerm = 1;
else {
double goldenRatio = (1 + Math.sqrt(5)) / 2;
nthTerm = (int) (Math.round(Math.pow(goldenRatio, n)
- Math.pow(1 - goldenRatio, n)) / Math.sqrt(5));
if (n % 2 == 1 && n < 45)
nthTerm++;
}
return nthTerm;
}
public static void main(String []args){
System.out.println(
fib(47)
);
}
}
方法fib2是您的代码,fib被转换为BigInteger.干杯
Method fib2 is your code, fib is the transformed into BigInteger. Cheers
这篇关于n≥1的斐波那契数列. 46爪哇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文