# How to check if a given number is Fibonacci number in C++

Hello Learners, today we are going to learn an interesting topic to check whether the given number is a Fibonacci or not in C++ coding. In this topic, we will solve this problem using two methods to test.

We have two formulas to check whether the given number is Fibonacci or not. That if it as a perfect square of either of the formulas mentioned below then we can say it is a Fibonacci number.

√(5*n*n+4) or √(5*n*n-4)

## C++: Program to check whether the given is Fibonacci or not

We will solve this problem using two codes,1) in the first code we will print the Fibonacci series up to less than our check number if that number is present in the obtained series then it is a Fibonacci number.

2) We implement the above-mentioned formula and check whether it is a perfect square or not, if it is a perfect square then the given number is a Fibonacci number.

Code1:

#include <iostream> using namespace std; class check_fibonacci { private: int a,b,n,c; public: void getdata() { cout<<"enter the number:"; cin>>n; } void checking_fibonacci() { if(n==0 || n==1) { cout<<"it is a fibonic number"; } else { a=0; b=1; c=a+b; while(c<n) { a=b; b=c; c=a+b; cout<<c<<"\t"; } if(c==n) { cout<<endl<<" it is a fibonic number"; } else { cout<<endl<<"not a fibonoc number"; } } } }; int main() { check_fibonacci obj; obj.getdata(); obj.checking_fibonacci(); return 0; }

Output:

enter the number:89 2 3 5 8 13 21 34 55 89 it is a fibonic number

Code 2:

#include <cmath> #include <iostream> using namespace std; class check_fibonnaci { private: int n,iRoot,iRoot1; double root,root1; public: void getdata() { cout<<"enter the number:"; cin>>n; } void checking_fibonacci() { root = sqrt(5.0*n*n+4.0); iRoot = root; root1 = sqrt(5.0*n*n-4.0); int iRoot1 = root1; if( root == iRoot || root1==iRoot1) { cout << "it is a fibonacci number:" << endl; } else { cout<<"not fibonacci number:"; } } }; int main() { check_fibonnaci obj; obj.getdata(); obj.checking_fibonacci(); return 0; }

Output:

enter the number:144 it is a fibonacci number:

This is all about How to check if a given number is a Fibonacci number in C++. If you have any doubts pls mention in the comment section below.

Also, read: C++ : Coin Detection Program using OpenCV

Sir! It has been easy one to understand fibonacci number

Indeed ,the best explanation had gone through

I love these tutorials…… Thanks sai…