2015-10-08 64 views
1

在我的一個java程序我試圖讀取一個數字,然後使用黃金比例(1.618034)找到下一個最小的斐波那契數字的指數。例如,如果我輸入100000,我應該找回「大於100000的最小斐波納契數是26,其值是121393」。黃金比例斐波那契地獄

該程序還應該通過索引(case 1下面的代碼)計算一個斐波那契數,我已經編碼到目前爲止,但我無法弄清楚如何解決上述問題(case 2)。我有一個可怕的老師,我真的不明白我需要做什麼。我不是要求代碼,只是一步一步的,我應該爲case 2做些什麼。我不能使用遞歸。感謝您的任何幫助。我嚴重地吮吸着包裹着我的頭。

import java.util.Scanner; 
public class Fibonacci { 

public static void main(String args[]) { 
    Scanner scan = new Scanner(System.in); 

    System.out.println("This is a Fibonacci sequence generator"); 
    System.out.println("Choose what you would like to do"); 
    System.out.println("1. Find the nth Fibonacci number"); 
    System.out.println("2. Find the smallest Fibonacci number that exceeds user given value"); 
    System.out.println("3. Find the two Fibonacci numbers whose ratio is close enough to the golden number"); 

    System.out.print("Enter your choice: "); 
    int choice = scan.nextInt(); 
    int xPre = 0; 
    int xCurr = 1; 
    int xNew = 0; 

    switch (choice) 
    { 
     case 1: 
      System.out.print("Enter the target index to generate (>1): "); 
      int index = scan.nextInt(); 

      for (int i = 2; i <= index; i++) 
      { 
       xNew = xPre + xCurr; 
       xPre = xCurr; 
       xCurr = xNew; 
      } 
      System.out.println("The " + index + "th number Fibonacci number is " + xNew); 
       break; 
     case 2: 
      System.out.print("Enter the target value (>1): "); 
      int value = scan.nextInt(); 

    } 
} 
} 
+1

你可以把它放在'while'循環中並計算斐波那契數,直到它大於'value'。 –

+0

就像我說的我真的不明白如何做這整個計算。我盡我所能,但我知道在一段時間內你有條件和聲明,但是我應該如何計算聲明? –

回答

0

首先,你應該明白這個黃金定理的故事是什麼。重點是,斐波那契數可遞歸計算,但也有第n個斐波納契數的公式:

φ(n)= [φ^ n - ( - φ)^( - n)] /√5

其中φ=(√5+ 1)/ 2是黃金比例(約1.61803)。現在,|(-φ)^( - 1)| < 1這意味着可以將φ(n)計算爲與φ^ n /√5最接近的整數(除非n = 1)。

因此,計算√5,計算φ,然後學習如何得到一個最接近真實變量值的整數,然後使用φ^ n /√5公式計算φ(n)(或者只使用「主要「[φ^ n - ( - φ)^( - n)] /√5公式),並在該循環中將φ(n)與用戶輸入的數字進行比較。當φ(n)超過用戶的數量時,請記住n和φ(n)。