How to useMathematical Formula in PHP

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

Check if a Given Number is Fibonacci Number in PHP

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

Similar Reads

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, …...

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....

Approach 2: Using while Loop

...