- Related Questions & Answers
- Add minimum number to an array so that the sum becomes even in C programming
- C Program for Tower of Hanoi
- C++ Program for Dijkstra’s shortest path algorithm?
- C/C++ Program for nth Catalan Number?
- C Program to Multiply two Floating Point Numbers?
- C program to find the length of a string?
- C Program to Check if all digits of a number divide it
- C Program to Check if a Given String is a Palindrome?
- Concatenate a string given number of times in C++ programming
- Write a program to Delete a Tree in C programming
- Write a C program to print “ Tutorials Point ” without using a semicolon
- Superperfect Number in C programming
- Sum of the nodes of a Singly Linked List in C Program
- Sum of first n natural numbers in C Program
- HTML DOM Input Number value Property

In this article, we will learn about the solution to the problem statement given below −

Given a number n, check whether n is a Fibonacci number or not

We all are aware that the nth Fibonacci number is the sum of the previous two Fibonacci numbers. But they also offer an interesting relation other than the recurrence relation.

A number is Fibonacci in nature if and only if (5*n2 + 4) or (5*n2 – 4) is a perfect square.

We will use this property to check whether a number is Fibonacci or not.

Now let’s see the implementation of the Python script −

import math # if x is perfect square def isPerfectSquare(x): s = int(math.sqrt(x)) return s*s == x # if n is a Fibinacci Number def isFibonacci(n): #if one of 5*n*n + 4 or 5*n*n - 4 or both is a perferct square return isPerfectSquare(5*n*n + 4) or isPerfectSquare(5*n*n - 4) for i in range(1,11): if (isFibonacci(i) == True): print (i,"is a Fibonacci Number") else: print (i,"is a not Fibonacci Number")

1 is a Fibonacci Number 2 is a Fibonacci Number 3 is a Fibonacci Number 4 is a not Fibonacci Number 5 is a Fibonacci Number 6 is a not Fibonacci Number 7 is a not Fibonacci Number 8 is a Fibonacci Number 9 is a not Fibonacci Number 10 is a not Fibonacci Number

All functions and variables are declared in the global frame as shown in the image below −

In this article, we learned the solution of identifying that the given number is Fibonacci or not.

Advertisements