A Fibonacci number is one which appears in the Fibonacci Sequence.
To check if a given number n occurs in the Fibonacci Sequence or not we only need to check if one or both of (5*n^2 + 4) or (5*n^2 – 4) is a perfect square or not (source: wiki).
Python code for the same:
(The code takes a number from standard input and prints on standard output whether the number is Fibonacci or not)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import math def isPerfectSquare(n): s = int(math.sqrt(n)) return s*s == n def main(): n = input() if isPerfectSquare(5*n*n - 4) or isPerfectSquare(5*n*n + 4): print "Is Fibonacci" else: print "Is Not Fibonacci" main() |