How to check if a number belongs to Fibonacci series in java in Java

What is Fibonacci Series

Fibonacci Series is a sequence of numbers in which each number(starting from the third number) is a sum of previous two numbers in the series and the first 2 elements of the series are 0 and 1. Thus the series becomes,
0, 1, 1, 2, 3, 5, 8, 13, 21 and so on….

Problem

Given a number as input, determine whether it belongs to the Fibonacci series or not. Example, input numbers such as 0, 5, 34, 55 belong to Fibonacci series but numbers such as 4, 9, 20, 52 do not belong to it.
We need to write a java program which reads a number as input and determines whether it will be among the members of Fibonacci series or not.

Program

The program to accomplish the above task is given below.

import java.util.Scanner;

public class FibonacciNumberChecker {

	public static void main(String[] args) {
		Scanner reader = new Scanner(System.in);
		System.out.println("Enter a number");
		// read the number to be checked
		int numberToCheck = reader.nextInt();
		// close the reader
		reader.close();
		int firstNumber = 0, secondNumber = 1, fibonacciNumber = 0;
		// loop till the current fibonacci number is less than the number to
		// check
		while (fibonacciNumber < numberToCheck) {
			// calculate the next fibonacci number
			fibonacciNumber = firstNumber + secondNumber;
			// move the fibonacci series ahead
			firstNumber = secondNumber;
			secondNumber = fibonacciNumber;
		}
		// compare the current fibonacci number with number to check
		if (numberToCheck == fibonacciNumber) {
			System.out.println("Number belongs to Fibonacci series");
		} else {
			System.out.println("Number does not belong to Fibonacci series");
		}
	}
}

Output

Enter a number
55
Number belongs to Fibonacci series

Enter a number
52
Number does not belong to Fibonacci series

Logic

The first step of this logic is to generate the Fibonacci series. For this, initialize first two members of the series(0 and 1) as two variables(firstMember and secondMember) and a third variable(fibonacciNumber) to hold the next member of the series. Initiate a loop which will generate the members of Fibonacci series based on the calculation :

fibonacciNumber = firstMember + secondMember;

Now firstMember variable is replaced with secondMember variable and secondMember is replaced with fibonacciNumber since we need to move forward with Fibonacci series generation.
This series is generated till the last number generated is less than the number we need to check. At the end of the loop, compare the last number generated is equal to the number to be checked. If they are same, the number belongs to the Fibonacci series else it does not belong to the series.

Let's tweak in

  1. Same logic can also be used to generate Fibonacci series till a given number. The only part omitted in that case will be the comparison of the numbers done after the loop.

Leave a Reply