Determining Whether a Number is a Fibonacci Number in Java: A Quick Guide

Determining Whether a Number is a Fibonacci Number in Java: A Quick Guide

·

2 min read

Definition

A sequence of numbers that follows a specific pattern. The first two numbers are always 0 and 1, and the third number is the sum of the first and second numbers.

Example of Fibonacci sequence

1,1,2,3,5,8,13,21,34,55...

Examples

IndexFibonacci NumberCalculation
000
111
210+1
321+1
431+2
552+3
683+5
7135+8
8218+13
93413+21
105521+34
118934+55
1214455+89
1323389+144
14377144+233
15610233+377
16987377+610

How to find the Fibonacci number at a specific index

Mathematical (Binet’s simplified formula)

    public static int fib(int num) {
        double goldenRatio = (1 + Math.sqrt(5)) / 2;
        return (int) Math.round(Math.pow(goldenRatio, num) / Math.sqrt(5));
    }

Recursive Function

    public static int fibRecursive(int num) {
        if (num == 0) return 0;
        else if (num == 1) return 1;
        else return fibRecursive(num - 2) + fibRecursive(num - 1);
    }

Loop

    public static int fib(int num) {
        if (num == 0) return 0;
        else if (num == 1) return 1;

        else {
            int result = 0;
            int iterA = 0;
            int iterB = 1;

            for (int i = 2; i <= num; i++) {

                result = iterA + iterB;
                iterA = iterB;
                iterB = result;

            }

            return result;
        }

    }

How to determine if a number is a Fibonacci number

If a number is a Fibonacci number, then either one or both of the expressions below will result in a perfect square:

Perfect Square

When x is a perfect square,

where root{x} must be an integer.

For example, 9 is a perfect square, but 3 is not.

Sample code

public static boolean isPerfectSquare(int temp) {
        int s = (int) Math.sqrt(temp);
        return (s * s == temp);
    }

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

Did you find this article valuable?

Support Eunhan's blog by becoming a sponsor. Any amount is appreciated!