在给定的值范围内查找最大的奇数Fibonacci数

时间:2017-12-31 05:46:29

标签: java

Ex:n1 = 100,n2 = 250,out = 233。

在这里,我必须找到给定范围集中最大的奇数斐波纳契数。如果一个奇怪的斐波纳契数不存在那么它应该返回0.我得到的输出为50次0然后是10次233.我的错误在哪里以及如何获得所需的输出?

public class Fibo {
    public static void main(String[] args) {
        try {
            int n1 = 100;
            int n2 = 250;
            int res = 0;

            if (n1 % 2 == 0) {
                n1 += 1;

                for (int i = n1; i < n2; i += 2) {
                    if (isPerfectSquare(5 * i * i + 4) || isPerfectSquare(5 * i * i - 4))
                        res = i;
                    System.out.println(res);
                }
            }
        } catch(Exception ignored) {
            System.out.println("0");
        }
    }

    public static boolean isPerfectSquare(int num) {
        double sqrt = Math.sqrt(num);
        int x = (int)sqrt;
        return Math.pow(sqrt, 2) == Math.pow(x, 2);
    }
}

2 个答案:

答案 0 :(得分:1)

public class Fibonacci {

    public static void main(String[] args) {
        System.out.println("Enter the starting range");
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        System.out.println("Enter the ending range");
        int r = sc.nextInt();
        int res = 0;
        for (int i = n; i <= r; i++) {
            if (isPerfectSquare(5 * i * i + 4) || isPerfectSquare(5 * i * i - 4))
                res = i;
            }
        System.out.println("The biggest odd number in the range is"+"  "+res);
    }

    public static boolean isPerfectSquare(int num) {
        double sqrt = Math.sqrt(num);
        int x = (int)sqrt;
        return Math.pow(sqrt, 2) == Math.pow(x, 2);
    }
}

答案 1 :(得分:-1)

public static int getLargestOddFibonacciBetween(int lo, int hi) {
    assert lo <= hi;

    int f0 = 0;
    int f1 = 1;
    int res = -1;

    while (f1 <= hi) {
        int val = f0 + f1;
        f0 = f1;
        f1 = val;

        if (val >= lo && val <= hi && isOdd(val))
            res = val;
    }

    return res;
}

private static boolean isOdd(int val) {
    return (val & 1) == 1;
}