Given a number ‘n’, how to check if n is a Fibonacci number. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, .. Examples :
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). Following is a simple program based on this concept.
C++
// C++ program to check if x is a perfect square
#include <bits/stdc++.h>
usingnamespacestd;
// A utility function that returns true if x is perfect
// square
boolisPerfectSquare(intx)
{
ints = sqrt(x);
return(s * s == x);
}
// Returns true if n is a Fibonacci Number, else false
boolisFibonacci(intn)
{
// n is Fibonacci if one of 5*n*n + 4 or 5*n*n - 4 or
// both is a perfect square
returnisPerfectSquare(5 * n * n + 4)
|| isPerfectSquare(5 * n * n - 4);
}
// A utility function to test above functions
intmain()
{
for(inti = 1; i <= 10; i++)
isFibonacci(i)
? cout << i << " is a Fibonacci Number \n"
: cout << i << " is a not Fibonacci Number \n";
return0;
}
// This code is contributed by Sania Kumari Gupta (kriSania804)
C
// C program to check if x is a perfect square
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
// A utility function that returns true if x is perfect
// square
boolisPerfectSquare(intx)
{
ints = sqrt(x);
return(s * s == x);
}
// Returns true if n is a Fibonacci Number, else false
boolisFibonacci(intn)
{
// n is Fibonacci if one of 5*n*n + 4 or 5*n*n - 4 or
// both is a perfect square
returnisPerfectSquare(5 * n * n + 4)
|| isPerfectSquare(5 * n * n - 4);
}
// A utility function to test above functions
intmain()
{
for(inti = 1; i <= 10; i++) {
if(isFibonacci(i))
printf("%d is a Fibonacci Number \n", i);
else
printf("%d is a not Fibonacci Number \n", i);
}
return0;
}
// This code is contributed by Sania Kumari Gupta (kriSania804)
Java
// Java program to check if x is a perfect square
classGFG
{
// A utility method that returns true if x is perfect square
staticbooleanisPerfectSquare(intx)
{
ints = (int) Math.sqrt(x);
return(s*s == x);
}
// Returns true if n is a Fibonacci Number, else false
staticbooleanisFibonacci(intn)
{
// n is Fibonacci if one of 5*n*n + 4 or 5*n*n - 4 or both
// is a perfect square
returnisPerfectSquare(5*n*n + 4) ||
isPerfectSquare(5*n*n - 4);
}
// Driver method
publicstaticvoidmain(String[] args)
{
for(inti = 1; i <= 10; i++)
System.out.println(isFibonacci(i) ? i + " is a Fibonacci Number":
i + " is a not Fibonacci Number");
}
}
//This code is contributed by Nikita Tiwari
Python
# python program to check if x is a perfect square
importmath
# A utility function that returns true if x is perfect square
defisPerfectSquare(x):
s =int(math.sqrt(x))
returns*s ==x
# Returns true if n is a Fibonacci Number, else false
defisFibonacci(n):
# n is Fibonacci if one of 5*n*n + 4 or 5*n*n - 4 or both
// javascript program to check if x is a perfect square
// A utility function that returns true if x is perfect square
functionisPerfectSquare( x)
{
let s = parseInt(Math.sqrt(x));
return(s * s == x);
}
// Returns true if n is a Fibonacci Number, else false
functionisFibonacci( n)
{
// n is Fibonacci if one of 5*n*n + 4 or 5*n*n - 4 or both
// is a perfect square
returnisPerfectSquare(5 * n * n + 4) ||
isPerfectSquare(5 * n * n - 4);
}
// A utility function to test above functions
for(let i = 1; i <= 10; i++)
isFibonacci(i)? document.write( i + " is a Fibonacci Number <br/>"):
document.write(i + " is a not Fibonacci Number <br/>") ;
// This code is contributed by Rajput-Ji
</script>
PHP
<?php
// PHP program to check if
// x is a perfect square
// A utility function that
// returns true if x is
// perfect square
functionisPerfectSquare($x)
{
$s= (int)(sqrt($x));
return($s* $s== $x);
}
// Returns true if n is a
// Fibonacci Number, else false
functionisFibonacci($n)
{
// n is Fibonacci if one of
// 5*n*n + 4 or 5*n*n - 4 or
// both is a perfect square
returnisPerfectSquare(5 * $n* $n+ 4) ||
isPerfectSquare(5 * $n* $n- 4);
}
// Driver Code
for($i= 1; $i<= 10; $i++)
if(isFibonacci($i))
echo"$i is a Fibonacci Number \n";
else
echo"$i is a not Fibonacci Number \n";
// This code is contributed by mits
?>
Output
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
Time Complexity: O(log N), where N is is the number that we square-root. Auxiliary Space: O(1)
Approach 2:
In this approach, we first handle the special case where the input number is 0 (which is a Fibonacci number). Then, we use a while loop to generate Fibonacci numbers until we find a Fibonacci number greater than or equal to the input number. If the generated Fibonacci number is equal to the input number, we return true. Otherwise, we check if either (5 * n * n + 4) or (5 * n * n – 4) is a perfect square, as per the formula mentioned in the original code.
This approach may be more efficient than the original code in some cases, especially for larger input values, as it generates Fibonacci numbers on-the-fly and stops as soon as it finds a Fibonacci number greater than or equal to the input number.
C++
#include <bits/stdc++.h>
usingnamespacestd;
boolisPerfectSquare(intn) {
introot = sqrt(n);
return(root * root == n);
}
boolisFibonacci(intn) {
if(n == 0) {
returntrue;
}
inta = 0, b = 1, c = 1;
while(c < n) {
a = b;
b = c;
c = a + b;
}
return(c == n || isPerfectSquare(5 * n * n + 4) || isPerfectSquare(5 * n * n - 4));
}
intmain() {
for(inti = 1; i <= 10; i++) {
if(isFibonacci(i)) {
cout << i << " is a Fibonacci number.\n";
} else{
cout << i << " is not a Fibonacci number.\n";
}
}
return0;
}
Java
importjava.util.*;
publicclassMain {
publicstaticbooleanisPerfectSquare(intn) {
introot = (int) Math.sqrt(n);
return(root * root == n);
}
publicstaticbooleanisFibonacci(intn) {
if(n == 0) {
returntrue;
}
inta = 0, b = 1, c = 1;
while(c < n) {
a = b;
b = c;
c = a + b;
}
return(c == n || isPerfectSquare(5* n * n + 4) || isPerfectSquare(5* n * n - 4));
}
publicstaticvoidmain(String[] args) {
for(inti = 1; i <= 10; i++) {
if(isFibonacci(i)) {
System.out.println(i + " is a Fibonacci number.");
} else{
System.out.println(i + " is not a Fibonacci number.");
return(c == n || IsPerfectSquare(5 * n * n + 4) || IsPerfectSquare(5 * n * n - 4));
}
publicstaticvoidMain() {
for(inti = 1; i <= 10; i++) {
if(IsFibonacci(i)) {
Console.WriteLine(i + " is a Fibonacci number.");
}
else{
Console.WriteLine(i + " is not a Fibonacci number.");
}
}
}
}
// This code is contributed by adityasha4x71
Javascript
functionis_perfect_square(n) {
let root = Math.floor(Math.sqrt(n));
return(root * root === n);
}
functionis_fibonacci(n) {
if(n === 0) {
returntrue;
}
let a = 0, b = 1, c = 1;
while(c < n) {
[a, b] = [b, c];
c = a + b;
}
returnc === n || is_perfect_square(5 * n * n + 4) || is_perfect_square(5 * n * n - 4);
}
for(let i = 1; i <= 10; i++) {
if(is_fibonacci(i)) {
console.log(i + " is a Fibonacci number.");
} else{
console.log(i + " is not a Fibonacci number.");
}
}
// Contributed by adityasha4x71
Output
1 is a Fibonacci number.
2 is a Fibonacci number.
3 is a Fibonacci number.
4 is not a Fibonacci number.
5 is a Fibonacci number.
6 is not a Fibonacci number.
7 is not a Fibonacci number.
8 is a Fibonacci number.
9 is not a Fibonacci number.
10 is not a Fibonacci number.
Time Complexity: O(log N), where N is is the number that we square-root. Auxiliary Space: O(1)
Approach 3:
This is another approach to check if a given number is Fibonacci number or not.
Steps:
To check if a given number is Fibonacci number or not, we do the following steps:
First check if the number is 0 or 1, then return true.
Then till the number comes do while loop.
In each iteration:
First calculate Fibonacci of that iteration.
Then check if it matches with given number or not.
If matches, return true.
If the value goes beyond, given number then return false.
Otherwise continue.
Below is the implementation of the above approach:
C++
// C++ program to check if a given number is
// Fibonacci number or not
#include <iostream>
usingnamespacestd;
// Function to check Fibonacci number
boolisFibonacci(intN)
{
if(N == 0 || N == 1)
returntrue;
inta = 0, b = 1, c;
while(true) {
c = a + b;
a = b;
b = c;
if(c == N)
returntrue;
elseif(c >= N) {
returnfalse;
}
}
}
intmain()
{
for(inti = 1; i <= 10; i++) {
if(isFibonacci(i)) {
cout << i << " is a Fibonacci number.\n";
}
else{
cout << i << " is not a Fibonacci number.\n";
}
}
return0;
}
// This code is contributed by Susobhan Akhuli
Java
publicclassGFG {
// Function to check if a given number is a Fibonacci
// number
staticbooleanisFibonacci(intN)
{
// Fibonacci numbers start with 0 and 1, so they are
// already Fibonacci
if(N == 0|| N == 1)
returntrue;
// Initialize two variables to track Fibonacci
// numbers
inta = 0, b = 1, c;
// Generate Fibonacci numbers until we reach N or a
// number greater than N
while(true) {
// Calculate the next Fibonacci number in the
// sequence
c = a + b;
a = b;
b = c;
// If the current Fibonacci number is equal to
// N, it is a Fibonacci number
if(c == N)
returntrue;
// If the current Fibonacci number is greater
// than N, it is not a Fibonacci number
elseif(c >= N) {
returnfalse;
}
}
}
publicstaticvoidmain(String[] args)
{
// Loop from 1 to 10 to check if each number is a
// Fibonacci number
for(inti = 1; i <= 10; i++) {
// Call the isFibonacci function to check if the
// number is a Fibonacci number
if(isFibonacci(i)) {
System.out.println(
i + " is a Fibonacci number.");
}
else{
System.out.println(
i + " is not a Fibonacci number.");
}
}
}
}
// This code is contributed by shivamgupta310570
Python3
# Python program to check if a given number is
# Fibonacci number or not
# Function to check Fibonacci number
defisFibonacci(N):
ifN ==0orN ==1:
returnTrue
a, b =0, 1
whileTrue:
c =a +b
a =b
b =c
ifc ==N:
returnTrue
elifc >=N:
returnFalse
# Driver Code
if__name__ =='__main__':
fori inrange(1, 11):
ifisFibonacci(i):
print(i, "is a Fibonacci number.")
else:
print(i, "is not a Fibonacci number.")
# This code is contributed by Aaysi Mishra
C#
// C# program to check if a given number is
// Fibonacci number or not
usingSystem;
publicclassGFG {
// Function to check if a given number is a Fibonacci
// number
staticboolIsFibonacci(intN)
{
// Fibonacci numbers start with 0 and 1, so they are
// already Fibonacci
if(N == 0 || N == 1)
returntrue;
// Initialize two variables to track Fibonacci
// numbers
inta = 0, b = 1, c;
// Generate Fibonacci numbers until we reach N or a
// number greater than N
while(true) {
// Calculate the next Fibonacci number in the
// sequence
c = a + b;
a = b;
b = c;
// If the current Fibonacci number is equal to
// N, it is a Fibonacci number
if(c == N)
returntrue;
// If the current Fibonacci number is greater
// than N, it is not a Fibonacci number
elseif(c >= N) {
returnfalse;
}
}
}
staticvoidMain(string[] args)
{
// Loop from 1 to 10 to check if each number is a
// Fibonacci number
for(inti = 1; i <= 10; i++) {
// Call the IsFibonacci function to check if the
// number is a Fibonacci number
if(IsFibonacci(i)) {
Console.WriteLine(
$"{i} is a Fibonacci number.");
}
else{
Console.WriteLine(
$"{i} is not a Fibonacci number.");
}
}
}
}
// This code is contributed by Susobhan Akhuli
Output
1 is a Fibonacci number.
2 is a Fibonacci number.
3 is a Fibonacci number.
4 is not a Fibonacci number.
5 is a Fibonacci number.
6 is not a Fibonacci number.
7 is not a Fibonacci number.
8 is a Fibonacci number.
9 is not a Fibonacci number.
10 is not a Fibonacci number.
Time Complexity: O(N), for iteration. Auxiliary Space: O(1)
This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!