Fibonacci序列算法

时间:2009-12-15 20:49:54

标签: java fibonacci

我试图在Fibonacci序列中找到第一个包含N位数的数字(N在500和2000范围内的某个位置)。我尝试使用以下代码执行此操作:

BigInteger num = BigInteger.valueOf(2);
BigInteger num1 = BigInteger.ONE;
BigInteger num2 = BigInteger.ONE;
int record = 0;
BigInteger TEN = BigInteger.valueOf(10);

public BigInteger run()
{
    BigInteger temp = BigInteger.ZERO;
    while(num2.compareTo(TEN.pow(SomeN - 1)) < 0)
    {
        if(num2.compareTo(TEN.pow(record + 1)) >= 0)
        {
            System.out.println(""+record);
            record++;
        }

        temp = num1.add(num2);
        num1 = num2;
        num2 = temp;

        num = num.add(BigInteger.ONE);
    }
    System.out.println(""+num);
    System.out.println(""+num2);
    return num2;
}

问题是,当我测试1500位数时,我得到的答案显然是错误的。我不知道应该是什么答案,我甚至在它周围检查了答案,以防我的算法以10的幂关闭(即我检查了1499位和1501),但无济于事。有谁看到了什么问题?

2 个答案:

答案 0 :(得分:1)

(删除基本提示的方式)

编辑:EP网站已备份,我在使用您的代码时得到的答案与网站接受的答案相符,对我来说是正确的。返回时间。

答案 1 :(得分:0)

当然,没有理由在这里使用大整数形式。 log10就足够了一行代码。在那里,完成那个......