Hot For Coding
PHP实现斐波那契

前几天我写了一版JavaScript与Python实现的,今天用PHP实现一下

什么是斐波那契

斐波那契数列指的是这样一个数列 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368........
这个数列从第3项开始,每一项都等于前两项之和

代码实现

<?php

$last1 = 0;
$last2 = 0;

function fibonacci() {
  global $last1, $last2;

  if ($last1 == 0) {
    $last1 = 1;
    $ret = $last1;
  } else if ($last2 == 0) {
    $last2 = 1;
    $ret = $last2;
  } else {
    $tmp = $last1 + $last2;
    $last2 = $last1;
    $last1 = $tmp;
    
    $ret = $tmp;
  }

  return $ret;
}

for ($i = 0; $i < 10; $i++) {
  echo fibonacci()."\n";
}

Output:

1, 1, 2, 3, 5, 8, 13, 21, 34, 55

TITLE: PHP实现斐波那契

LINK: https://www.qttc.net/264_php_fibonacci.html

NOTE: 转载内容请注明出处