Skip to content

Instantly share code, notes, and snippets.

@fre2mansur
Created July 27, 2019 07:15
Show Gist options
  • Save fre2mansur/150400f71ea99d74d5d8ba82c66fea33 to your computer and use it in GitHub Desktop.
Save fre2mansur/150400f71ea99d74d5d8ba82c66fea33 to your computer and use it in GitHub Desktop.
Step one: check the given number is fibonacci or not.
$input = array(1,22,9,0);
var_dump(nextFibonacci($input)); //output [2,34,13]
function nextFibonacci($input) {
foreach($input as $i) {
while($i>=0) {
$store[] = $i;
if(isFibonacci($i))
break;
$i--;
}
$last = end($store);
if($last == 0) {
$output[] = 1;
} else {
$output[] = round($last/0.618);
}
}
return $output;
}
//Checking for square root
function isPerfectSquare($x)
{
$s = (int)(sqrt($x));
return ($s * $s == $x);
}
// n is Fibinacci if one of
// 5*n*n + 4 or 5*n*n - 4 or
// both is a perferct square
function isFibonacci($n)
{
return isPerfectSquare(5 * $n * $n + 4) || isPerfectSquare(5 * $n * $n - 4);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment