Open In App

Check if a Given Number is Fibonacci Number in PHP

Last Updated : 02 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a number N, the task is to check whether the given number is a Fibonacci number or not.

Examples:

Input: 21
Output: Fibonacci Number

Input: 35
Output: Not a Fibonacci Number

What is the Fibonacci Series?

The Fibonacci series is the sequence where each number is the sum of the previous two numbers of the sequence. The first two numbers of the Fibonacci series are 0 and 1 and are used to generate the Fibonacci series.

What is Fibonacci Number?

The number that are present in Fibonacci Series is known as Fibonacci number. The Fibonacci numbers are the following integer sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …

There are three methods to check the given number is Fibonacci Number or not, these are:

Approach 1: Using Mathematical Formula

The Fibonacci Sequence can be generated using a mathematical formula. One such formula is Binet’s formula. This formula is an explicit formula to find the nth term of the Fibonacci sequence. Using this formula, we can check if a given number n is a Fibonacci number. A number is Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square.

Example:

PHP




<?php 
  
function isPerfectSquare($n) {
    $s = (int)sqrt($n);
    return ($s * $s == $n);
}
  
function isFibonacci($n) {
    return isPerfectSquare(5 * $n * $n + 4) 
        || isPerfectSquare(5 * $n * $n - 4);
}
  
// Driver code
$n = 13;
  
if (isFibonacci($n)) {
    echo "Fibonacci Number";
} else {
    echo "Not a Fibonacci Number";
}
  
?>


Output

Fibonacci Number

Approach 2: Using while Loop

PHP loop can generate Fibonacci numbers until reaching a number greater than or equal to the given number. If the given number is found during the process, it is a Fibonacci number.

Example:

PHP




<?php 
  
function isFibonacci($n) {
    $a = 0;
    $b = 1;
  
    while ($b < $n) {
        $temp = $a + $b;
        $a = $b;
        $b = $temp;
    }
  
    return ($b == $n);
}
  
// Driver code
$n = 13;
  
if (isFibonacci($n)) {
    echo "Fibonacci Number";
} else {
    echo "Not a Fibonacci Number";
}
  
?>


Output

Fibonacci Number


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads