Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check whether a number is a Fibonacci number or not JavaScript
We are required to write a JavaScript function that takes in a number and returns a boolean based on the fact whether or not it comes in the fibonacci series.
For example −
If the function call is like this −
fibonacci(12); fibonacci(89); fibonacci(55); fibonacci(534);
Then the output should be −
false true true false
What is the Fibonacci Series?
The Fibonacci series is a sequence where each number is the sum of the two preceding ones: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Method 1: Using Recursive Approach
Now, let's write a recursive solution to this problem:
const fibonacci = (query, count = 1, last = 0) => {
if(count
false
true
true
false
Method 2: Using Iterative Approach
A more efficient iterative solution that generates Fibonacci numbers until we reach or exceed the query:
function isFibonacci(n) {
if (n === 0 || n === 1) return true;
let a = 0, b = 1;
while (b
false
true
true
true
true
Method 3: Using Mathematical Formula
A number n is Fibonacci if one of (5*n² + 4) or (5*n² - 4) is a perfect square:
function isPerfectSquare(n) {
let sqrt = Math.sqrt(n);
return sqrt === Math.floor(sqrt);
}
function isFibonacciMath(n) {
return isPerfectSquare(5*n*n + 4) || isPerfectSquare(5*n*n - 4);
}
console.log(isFibonacciMath(55));
console.log(isFibonacciMath(89));
console.log(isFibonacciMath(12));
console.log(isFibonacciMath(100));
true
true
false
false
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Recursive | O(n) | O(n) | Medium |
| Iterative | O(n) | O(1) | High |
| Mathematical | O(1) | O(1) | Low |
Conclusion
The iterative approach is most practical for checking Fibonacci numbers, offering good performance and readability. The mathematical method is fastest but harder to understand.
