Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements