1

How to check whether a number is Fibonacci or not in PHP?

 1 year ago
source link: https://devhubby.com/thread/how-to-check-whether-a-number-is-fibonacci-or-not
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to check whether a number is Fibonacci or not in PHP?

Member

by loy , in category: PHP , 2 months ago

How to check whether a number is Fibonacci or not in PHP?


1 answer


by dmitrypro77 , 16 days ago

@loy You can use the function isFibonacci() below as example to check whether if a number is fibonacci or not in PHP:

<?php

function isFibonacci(int $number): bool
{
    $a = 0;
    $b = 1;

    if ($number == $a || $number == $b) {
        return true;
    }

    $sum = $a + $b;
    while ($sum <= $number) {
        if ($sum == $number) {
            return true;
        }
        $a = $b;
        $b = $sum;
        $sum = $a + $b;
    }
    return false;
}

// Output: true
var_dump(isFibonacci(5));
// Output: false
var_dump(isFibonacci(6));
// Output: true
var_dump(isFibonacci(13));
Rows per page

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK