How to do Fibonacci sequence in php

爱喝马黛茶的安东尼
Release: 2023-02-25 10:26:01
Original
3528 people have browsed it

How to do Fibonacci sequence in php

Fibonacci sequence, also known as the golden section sequence, was named after the mathematician Leonardoda Fibonacci used rabbit reproduction as an example. It is introduced, so it is also called the "Rabbit Sequence", which refers to such a sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34,..., simply put, the Fibonacci Sequence is Series elements, the first two elements are added to get the next element, starting from 0 and 1.

How to implement Fibonacci sequence in PHP?

In this article, we will introduce to you how to implement the Fibonacci sequence with PHP. 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
Copy after login

Related recommendations: "php tutorial"

Method 1: Use recursion

Recursion is how we call the same function repeatedly until a basic condition is matched to end the recursion.


        
Copy after login

Output:

0 1 1 2 3 5 8 13 21 34
Copy after login
Copy after login

Method 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.


        
Copy after login

Output:

0 1 1 2 3 5 8 13 21 34
Copy after login
Copy after login

The above is the detailed content of How to do Fibonacci sequence in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!