Given a number ‘n’, how to check if n is a Fibonacci number.
A simple way is to generate Fibonacci numbers until the generated number is greater than or equal to ‘n’. Following is an interesting property about Fibonacci numbers that can also be used to check if a given number is Fibonacci or not.
A number is Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square (Source: Wiki).
Read full article from How to check if a given number is Fibonacci number? | GeeksforGeeks
A simple way is to generate Fibonacci numbers until the generated number is greater than or equal to ‘n’. Following is an interesting property about Fibonacci numbers that can also be used to check if a given number is Fibonacci or not.
A number is Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square (Source: Wiki).
bool
isPerfectSquare(
int
x)
{
int
s =
sqrt
(x);
return
(s*s == x);
}
// Returns true if n is a Fibinacci Number, else false
bool
isFibonacci(
int
n)
{
// n is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both
// is a perferct square
return
isPerfectSquare(5*n*n + 4) ||
isPerfectSquare(5*n*n - 4);
}
No comments:
Post a Comment