斐波那契数列检查(检查用户输入的数字是否为斐波那契数)

时间:2018-10-04 14:26:33

标签: java fibonacci

我如何要求用户使用Scanner输入任何数字,然后向他们显示输入的数字是否是斐波那契数字。

int[] ar = new int[200];
System.out.print(0+" "+1+" ");
for (int i = 2; i < 110; i++) {
    ar[0] = 0;
    ar[1] = 1;
    ar[i] = ar[i-2] + ar[i-1];
    System.out.print(ar[i]+" ");
}
//The code above prints out some fibonacci numbers

System.out.println(Type in a number: );
int x = scan.nextInt();

1 个答案:

答案 0 :(得分:0)

看看下面的代码片段。用用户输入的内容替换for生成的值。

public static void main(String[] args) {
    for(int i = 1; i < 100; i ++) {
        System.out.println("Is " + i + " fibonacci: " + isFibonacci(i));
    }
}

public static boolean isFibonacci(int x) {
    return isPerfectSquare(5*x*x + 4) || isPerfectSquare(5*x*x - 4);
}

public static boolean isPerfectSquare(double x) {
    double squareRoot = Math.sqrt(x);
    return ((squareRoot - Math.floor(squareRoot)) == 0);
}

关于其背后的数学:https://math.stackexchange.com/questions/9999/checking-if-a-number-is-a-fibonacci-or-not/10002#10002