Home>Article>Backend Development> How to implement Fibonacci sequence in PHP? (code example)
Fibonacci sequence, also known as the golden section sequence, was introduced by the mathematician Leonardoda Fibonacci using rabbit reproduction as an example, so it is also called the "rabbit sequence" ", refers to such a sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34,..., simply put, the Fibonacci sequence is a series of elements, the first two elements are added together Get the next element, starting from 0 and 1.
In this article, we will introduce to youHow to use PHP to implement the Fibonacci sequence. Given a number n, we need to find the Fibonacci sequence up to the nth term.
Example:
输入:10 输出:0 1 1 2 3 5 8 13 21 34 输入:15 输出:0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Method 1: Using recursion
Recursion is how we call the same function repeatedly until the basic condition is matched to end the recursion.
Output:
0 1 1 2 3 5 8 13 21 34Method 2: Using iterative method
First, we initialize the first and second numbers to 0 and 1. Then, we print the first and second numbers. Then we send the process to the iterative while loop where we get the next number by adding the previous two numbers, at the same time we swap the first number with the second number and the second number with the third number.
Output:
0 1 1 2 3 5 8 13 21 34Related video tutorial recommendation: "PHP Tutorial"
This article is about implementing Fibonacci in PHP An introduction to the method of sequence of numbers, I hope it will be helpful to friends who need it!
The above is the detailed content of How to implement Fibonacci sequence in PHP? (code example). For more information, please follow other related articles on the PHP Chinese website!