[英]How to check if a given number is Fibonacci number?
我想检查我的电话号码是不是斐波那契?
isFibonacci(13);
function isFibonacci( $testedNumber, $a = 1, $b = 1 )
{
if( $testedNumber == 0 || $testedNumber == 1 )
return true;//returning true for 0 and 1 right away.
$nextFib = $a + $b;//getting the next number in the sequence
if( $nextFib > $testedNumber )
return false;//if we have passed the tested number, it's not in the sequence
else if( $nextFib == $testedNumber )
return true;//if we have a perfect match, the tested number is in the sequence
else
isFibonacci( $testedNumber, $b, $nextFib );//otherwise, get the next fibonacci number and repeat.
}
<?php
function getFibonicciIndex($number)
{
$log_base = (1+sqrt(5))/2;
$index = log(($number*sqrt(5)-(1/2)), $log_base);
return floor($index)+1;
}
function getFibonicciNumber($term)
{
$a = (1+sqrt(5))/2;
$b = (1-sqrt(5))/2;
$fibonicci_number = (pow($a, $term)-pow($b, $term))/sqrt(5);
return $fibonicci_number;
}
$number = 14;
$index = getFibonicciIndex($number);
$index_value = getFibonicciNumber($index);
echo ($number == $index_value) ? "yes" : "no";
//此逻辑实现了找到斐波那契数列及其索引的最佳规则。 首先,我们假设给定的编号。 是斐波那契数列的一部分,并尝试获取指数..然后对于给定的索引,我们计算斐波那契数并将其等同以验证
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.