Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS:checking if number belongs to Fibonacci sequence(without loop)

Is there an efficient way to check if number belongs to Fibonacci sequence?

I've seen many examples with a loop that creates the sequence in an array and checks every time if newly generated number of the sequence is equal to the input number. Is there another way?

like image 245
Ashot Tarumyan Avatar asked Jan 16 '26 23:01

Ashot Tarumyan


1 Answers

http://www.geeksforgeeks.org/check-number-fibonacci-number/

This link details that there is a special quality about fibonacci numbers that means that a number is Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square.

So,

function (num) {
    if (isSquare(5*(num*num)-4) || isSquare(5*(num*num)+4)) {
       return true;
    } else { return false; }
}

Then isSquare would just be a simple checking function.

Edit: Worth noting that while this is a much more efficient and easy way to find fibonacci numbers, it does have an upper bound. At about the 70th Fibonacci number and above, you may see issues because the numbers are too large.

like image 82
EvSunWoodard Avatar answered Jan 19 '26 11:01

EvSunWoodard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!