Home >Backend Development >PHP Tutorial >Recursion and recursion to implement Fibonacci sequence algorithm

Recursion and recursion to implement Fibonacci sequence algorithm

WBOY
WBOYOriginal
2016-08-08 09:22:051858browse
<?php
/*
f(n)=f(n-1)+f(n-2)
f(0)=0
f(1)=1
*/
function Fibonacci($n)
{
	if($n<=0)
	{
		return 0;
	}
	if($n==1)
	{
		return 1;
	}
	return f(n-1)+f(n-2);
}

/*
递推实现
*/
function Fibonacci1($n)
{
	if($n<=0)
	{
		return 0;
	}
	if($n==1)
	{
		return 1;
	}
	$fibNMinus
	$fibNMinusTwo=0;
	$fibN=0;
	for($i=2;$i<=n;$i++)
	{
		$fibN=$fibNMinusOne+$fibNMinusTwo;
		$fibNMinusTwo=$fibNMinusOne;
		$fibNMinus
	}

	return $fibN;
}

Copyright Statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.

The above has introduced the recursion and recursion to implement the Fibonacci sequence algorithm, including aspects of the algorithm. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn