Java:检查数字是否属于Fibonacci序列

时间:2012-11-11 23:28:29

标签: java fibonacci

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

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));

    }
}

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

3 个答案:

答案 0 :(得分:8)

您在fib2 <= n时继续循环,因此当您离开循环时,fib2始终为> n,因此它返回false

答案 1 :(得分:1)

/**
 * @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));

}

答案 2 :(得分:0)

这很有效。我不确定效率......但这是一个万无一失的计划,

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

}