【问题标题】:Golden Ratio Fibonacci Hell黄金比例斐波那契地狱
【发布时间】:2016-01-05 10:10:53
【问题描述】:

在我的一个 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();

    }
}
}

【问题讨论】:

  • 您可以将其放入while 循环中并计算斐波那契数,直到它大于value。
  • 就像我说的,我真的不明白如何进行整个计算。我正在尽我最大的努力,但我知道通过 while 循环你有条件和语句,但是我应该为语句计算放什么?

标签: fibonacci


【解决方案1】:

首先,您应该了解这个黄金配给故事的全部内容。关键是,斐波那契数可以递归计算,但也有第 n 个斐波那契数的公式:

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

其中 φ = (√5 + 1)/2 是黄金分割率(约 1.61803)。现在,|(-φ)^(-1)|

所以,计算 √5,计算 φ,然后学习如何得到一个最接近实变量值的整数,然后使用 φ^n/√5 公式计算 φ(n)(或者只使用“main " [φ^n - (-φ)^(-n)]/√5 公式)在一个循环中,并在该循环中将 φ(n) 与用户输入的数字进行比较。当 φ(n) 超过用户数时,记住 n 和 φ(n)。

【讨论】:

    猜你喜欢
    • 2017-07-07
    • 2018-08-18
    • 2013-02-09
    • 1970-01-01
    • 2019-05-28
    • 2012-12-29
    • 1970-01-01
    • 2015-06-05
    • 2014-05-23
    相关资源
    最近更新 更多