How to use the Golden Ratio Formula In Javascript

In this approach, we use the property that a number is a Fibonacci number if and only if one of (5 * n^2 + 4) or (5 * n^2 – 4) is a perfect square. We implement a function to check for a perfect square and then use it in the main function to determine if the given number is a Fibonacci number or not.

Example: To check if a number is Fibonacci number or not using golden ratio.

Javascript




// A function that returns true if x is a perfect square
 
function isPerfectSquare(x) {
  let sqrt = parseInt(Math.sqrt(x));
  return sqrt * sqrt == x;
}
 
// Returns true if n is a Fibonacci Number, else false
 
function isFibonacci(n) {
  return isPerfectSquare(5 * n * n + 4) || isPerfectSquare(5 * n * n - 4);
}
 
// Example usage:
let i = 54;
if (isFibonacci(i)) {
  console.log(i + " is a Fibonacci number.");
} else {
  console.log(i + " is not a Fibonacci number.");
}


Output

54 is not a Fibonacci number.

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

Similar Reads

Iterative Fibonacci Number Checking

This approach involves iterating through generating Fibonacci numbers until we either find a match with the given number or reach a Fibonacci number greater than the given number....

Using the Golden Ratio Formula

...

Iterative On-the-Fly Fibonacci Generation

In this approach, we use the property that a number is a Fibonacci number if and only if one of (5 * n^2 + 4) or (5 * n^2 – 4) is a perfect square. We implement a function to check for a perfect square and then use it in the main function to determine if the given number is a Fibonacci number or not....