2015-10-04 30 views
1

我有兩個算法打印1000位數的第一個斐波那奇數字,但似乎我錯過了一些東西。1000個數字(PE#25)斐波那契數字的尋找指數

Algo 1

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++; 
    } 
} 
} 

Output

它的輸出也很長,但最後卻寫道:

curr : 4781.0Digits : 999 
curr : 4782.0Digits : 999 
curr : 4783.0Digits : 999 
curr : 4784.0Digits : 999 
curr : 4785.0Digits : 1000 
curr : 4786.0Digits : 1000 
curr : 4787.0Digits : 1000 
curr : 4788.0Digits : 1000 
curr : 4789.0Digits : 1000 
curr : 4790.0Digits : 1001 

看來,4785是答案,但扣!它的不正確。所以我通過反向求解Wolfram方程來嘗試更多的數學方法。

ans = (1000 + (float) Math.log10(fiveSqrt))/ (float) Math.log10(phi); 
System.out.println(ans); 

輸出:4786.6445 再次,相同的。我錯過了什麼嗎?

+0

呃...也許是想要>> 1000位數的最小斐波那契數的值<< –

+1

你需要斐波那契數還是該數的序數? – laune

+0

爲什麼你認爲這個公式會給你一個具有一定數字的斐波那契數字?我記得遞歸計算斐波那契數 - 不是用一個簡單的方程,比如將常數加到所需的數字中。我不明白這是如何工作的,但這不是一個數學網站。您可以嘗試http://math.stackexchange.com。 –

回答

3

閱讀this教程以獲得完整的理解。你曲解了算法,你已經使用Math.round(noOfDigits)這是不正確,你應該做的是:

  1. 計算noOfDigits,正如你在算法
  2. 提取整數部分做。
  3. 向其中添加'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++; 
    } 
    

    這給了我答案:4782.0這是正確的。