Java:检查数字是否属于斐波那契数列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13336593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 12:19:30  来源:igfitidea点击:

Java: check if number belongs to Fibonacci sequence

javafibonacci

提问by helena.pimentel

I'm supposed to write a code which checks if a given number belongs to the Fibonacci sequence. After a few hours of hard work this is what i came up with:

我应该编写一个代码来检查给定的数字是否属于斐波那契数列。经过几个小时的努力,这就是我想出的:

public class TP2 {

    /**
     * @param args
     */

    public static boolean ehFibonacci(int n) {
        int fib1 = 0;
        int fib2 = 1;
        do {
            int saveFib1 = fib1;
            fib1 = fib2;
            fib2 = saveFib1 + fib2;
            }
        while (fib2 <= n);

        if (fib2 == n)
            return true;
        else
            return false;

    }
    public static void main(String[] args) {
        int n = 8;
        System.out.println(ehFibonacci(n));

    }
}

I must be doing something wrong, because it always returns "false". Any tips on how to fix this?

我一定是做错了什么,因为它总是返回“false”。有关如何解决此问题的任何提示?

回答by John3136

You continue the loop while fib2 <= n, so when you are out of the loop, fib2 is always > n, and so it returns false.

您继续循环 while fib2 <= n,因此当您退出循环时, fib2 始终为> n,因此它返回false

回答by jakub.petr

/**
 * @param args
 */

public static boolean ehFibonacci(int n) {
    int fib1 = 0;
    int fib2 = 1;
    do {
        int saveFib1 = fib1;
        fib1 = fib2;
        fib2 = saveFib1 + fib2;
        }
    while (fib2 < n);

    if (fib2 == n)
        return true;
    else
        return false;

}
public static void main(String[] args) {
    int n = 5;
    System.out.println(ehFibonacci(n));

}

回答by Nithya

This works. I am not sure about efficiency..but this is a foolproof program,

这有效。我不确定效率……但这是一个万无一失的程序,

public class isANumberFibonacci {

public static int fibonacci(int seriesLength) {
    if (seriesLength == 1 || seriesLength == 2) {
        return 1;
    } else {
        return fibonacci(seriesLength - 1) + fibonacci(seriesLength - 2);
    }
}

public static void main(String args[]) {
    int number = 4101;
    int i = 1;
    while (i > 0) {
        int fibnumber = fibonacci(i);
        if (fibnumber != number) {
            if (fibnumber > number) {
                System.out.println("Not fib");
                break;
            } else {
                i++;
            }
        } else {
            System.out.println("The number is fibonacci");
            break;
        }
    }
}

}

}