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
Contact Us