Iterative On-the-Fly Fibonacci Generation
In this approach, we first handle the special case where the input number is 0 (which is a Fibonacci number). Then, we use a while loop to generate Fibonacci numbers until we find a Fibonacci number greater than or equal to the input number.
If the generated Fibonacci number is equal to the input number, we return true. Otherwise, we check if either (5 * n * n + 4) or (5 * n * n – 4) is a perfect square, as per the formula mentioned in the original code.
This approach may be more efficient than the original code in some cases, especially for larger input values, as it generates Fibonacci numbers on-the-fly and stops as soon as it finds a Fibonacci number greater than or equal to the input number.
Example: To check if a number is fibonacci number or not using on the fly method.
Javascript
function isPerfectSquare(n) { let root = parseInt(Math.sqrt(n)); return root * root == n; } function isFibonacci(n) { if (n == 0) { return true ; } let a = 0, b = 1, c = 1; while (c < n) { a = b; b = c; c = a + b; } return ( c == n || isPerfectSquare(5 * n * n + 4) || isPerfectSquare(5 * n * n - 4) ); } for (let i = 1; i <= 10; i++) { if (isFibonacci(i)) { console.log(i + " is a Fibonacci number." ); } else { console.log(i + " is not a Fibonacci number." ); } } |
1 is a Fibonacci number. 2 is a Fibonacci number. 3 is a Fibonacci number. 4 is not a Fibonacci number. 5 is a Fibonacci number. 6 is not a Fibonacci number. 7 is not a Fibonacci number. 8 is a Fibona...
How to Check if a Given Number is Fibonacci Number in JavaScript ?
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. Checking for Fibonacci numbers involves verifying whether a given number appears in this sequence. The first few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, and 89, and so on. There are various approaches to check if a number is a Fibonacci number in Javascript or not which are as follows:
Table of Content
- Iterative Fibonacci Number Checking
- Using the Golden Ratio Formula
- Iterative On-the-Fly Fibonacci Generation