Java 查找1000位斐波那契数的索引(PE#25)

Java 查找1000位斐波那契数的索引(PE#25),java,Java,我有两种算法来打印第一个1000位数的斐波那契数,但我似乎遗漏了一些东西 algo1 public class ab{ public static void main(String[] args){ float phi = (float) 1.618033989; float curr = 1; float noOfDigits = 0; float ans; float fiveSqrt = (float) Math.sqrt(5);

我有两种算法来打印第一个1000位数的斐波那契数,但我似乎遗漏了一些东西

algo1

public class ab{
public static void main(String[] args){
     float phi = (float) 1.618033989;
     float curr = 1;
     float noOfDigits = 0;
     float ans;
     float fiveSqrt = (float) Math.sqrt(5);
    while(noOfDigits< 1001){
        noOfDigits = (curr*Math.log10(phi)) - Math.log10(fiveSqrt);
        System.out.println("curr : " + curr + "Digits : " + Math.round(noOfDigits));
    curr++;
    }
}
}
看起来,4785是答案,但很快!这是不正确的。所以我尝试了一种更为数学化的方法,用相反的方式解Wolfram方程

ans = (1000 + (float) Math.log10(fiveSqrt))/ (float) Math.log10(phi);
System.out.println(ans);
输出:
4786.6445
还是一样。我遗漏了什么吗

阅读教程以获得完整的理解。您误解了算法,使用了
Math.round(noOfDigits)
这是不正确的,您应该做的是:

  • 计算noOfDigits,就像在算法中一样
  • 提取整数部分
  • 将“1”添加到它

    long roundedNumber;
    while(noOfDigits< 1001){
    noOfDigits = (curr*Math.log10(phi)) - Math.log10(fiveSqrt);
    roundedNumber = (long)noOfDigits + 1;
    System.out.println("curr : " + curr + "Digits : " + Math.round(roundedNumber));
    curr++;
    }
    
    long roundedNumber;
    而(无数字<1001){
    noOfDigits=(curr*Math.log10(phi))-Math.log10(fiveSqrt);
    roundedNumber=(长)noOfDigits+1;
    System.out.println(“curr:+curr+”数字:“+Math.round(roundedNumber));
    curr++;
    }
    
    这给了我答案:
    4782.0
    这是正确的


  • 嗯。。。也许你想要>>值你需要斐波那契数还是该数的序数?为什么你相信这个方程会给你一个有一定位数的斐波那契数?我记得递归计算斐波那契数,而不是用一个简单的方程,比如将所需数字的#加到常数上。我不知道这是怎么回事,但这不是一个数学网站。你可以试试。哦,是的@StephenC,我的天bad@StevenHansen,因为这是数学证明的黄金比例。
    long roundedNumber;
    while(noOfDigits< 1001){
    noOfDigits = (curr*Math.log10(phi)) - Math.log10(fiveSqrt);
    roundedNumber = (long)noOfDigits + 1;
    System.out.println("curr : " + curr + "Digits : " + Math.round(roundedNumber));
    curr++;
    }