Checking for Fibonacci numbers in JavaScript


We are required to write a JavaScript function that takes in a number and checks whether it is a Fibonacci number or not (i.e., it falls in Fibonacci series or not).

Our function should return true if the number is a Fibonacci number, false otherwise.

The code for this will be −

const num = 2584;
const isFibonacci = num => {
   if(num === 0 || num === 1){
      return true;
   }
   let prev = 1;
   let count = 2;
   let temp = 0;
   while(count <= num){
      if(prev + count === num){
         return true;
      };
      temp = prev;
      prev = count;
      count += temp;
   };
   return false;
};
console.log(isFibonacci(num));
console.log(isFibonacci(6765));
console.log(isFibonacci(45));
console.log(isFibonacci(8767));

Following is the output on console −

true
true
false
false

Updated on: 09-Oct-2020

941 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements