Home Backend Development PHP Tutorial N algorithms for Fibonacci sequence in PHP

N algorithms for Fibonacci sequence in PHP

Sep 01, 2020 pm 01:17 PM
php algorithm Fibonacci Sequence

N algorithms for Fibonacci sequence in PHP

Preface

Some time ago, I encountered the conventional recursive method of optimizing the calculation of the Fibonacci sequence, but once Time did not come up with a good method in time, so I searched for relevant information later and summarized a variety of calculation solutions, so I shared it with everyone to communicate and learn together.

Recommended: "PHP Video Tutorial"

What are Fibonacci numbers

Fibonacci The Fibonacci sequence, also known as the golden section sequence, was introduced by the mathematician Leonardoda Fibonacci using rabbit breeding as an example, so it is also called the "rabbit sequence". It refers to this A sequence of numbers: 1, 1, 2, 3, 5, 8, 13, 21, 34,... Mathematically, the Fibonacci sequence is defined recursively as follows: F(1)=1, F (2)=1, F(n)=F(n - 1) F(n - 2) (n ≥ 3, n ∈ N*).

Now that we knowFibonacci numbers, then we will use a variety of different methods to calculate and obtain the Nth Fibonacci number.

Ordinary recursion

This method is the most conventional, directly based on the definitionF(n)=F(n - 1) F(n - 2 )Recursive calculation is enough, but the performance is the lowest.

/**
 * 普通递归
 * @param int $n
 * @return int
 */function fib($n = 1){    // 低位处理
    if ($n < 3) {        return 1;
    }    // 递归计算前两位
    return fib($n - 1) + fib($n - 2);
}
Copy after login

Recursive optimization

As you can see from the above recursive method, a lot of repeated calculations are performed, and the performance is extremely poor. If N is larger, the number of calculations will be too many. It's terrible. Well, since repeated calculations affect performance, optimization starts with reducing repeated calculations, that is, storing previously calculated calculations, thus avoiding too many repeated calculations and optimizing the recursive algorithm.

/**
 * 递归优化
 * @param int $n
 * @param int $a
 * @param int $b
 * @return int
 */function fib_2($n = 1, $a = 1, $b = 1){    if ($n > 2) {        // 存储前一位,优化递归计算
        return fib_2($n - 1, $a + $b, $a);
    }    return $a;
}
Copy after login

Memory bottom-up

Bottom-up calculates the sub-problem of Fibonacci numbers iteratively and stores the calculated value, passing the calculated value Calculation. Use for loops to reduce double calculation problems caused by recursion.

/**
 * 记忆化自底向上
 * @param int $n
 * @return int
 */function fib_3($n = 1){
    $list = [];    for ($i = 0; $i <= $n; $i++) {        // 从低到高位数,依次存入数组中
        if ($i < 2) {
            $list[] = $i;
        } else {
            $list[] = $list[$i - 1] + $list[$i - 2];
        }
    }    // 返回最后一个数,即第N个数
    return $list[$n];
}
Copy after login

Iterate from the bottom up

The lowest bit is initialized and assigned, use for to iterate from the low bit to the high bit to obtain the Nth number .

/**
 * 自底向上进行迭代
 * @param int $n
 * @return int
 */function fib_4($n = 1){    // 低位处理
    if ($n <= 0) {        return 0;
    }    if ($n < 3) {        return 1;
    }
    $a = 0;
    $b = 1;    // 循环计算
    for ($i = 2; $i < $n; $i++) {
        $b = $a + $b;
        $a = $b - $a;
    }    return $b;
}
Copy after login

Formula method

By understanding the relationship between the Fibonacci sequence and the golden ratio, use the golden ratio to calculate the N Fibonacci numbers.

/**
 * 公式法
 * @param int $n
 * @return int
 */function fib_5($n = 1){    // 黄金分割比
    $radio = (1 + sqrt(5)) / 2;    // 斐波那契序列和黄金分割比之间的关系计算
    $num = intval(round(pow($radio, $n) / sqrt(5)));    return $num;
}
Copy after login

Invincible Beating Method

I won’t go into detail about this method. Everyone knows it, but don’t try it easily...

N algorithms for Fibonacci sequence in PHP
/**
 * 无敌欠揍法
 * @param int $n
 * @return int
 */function fib_6($n = 1){    // 列举了30个数
    $list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269];    return $list[$n];
}
Copy after login

Finally

Okay, I just wrote a few solutions. If there is something wrong, Please point it out and I will revise it in time. If you have other calculation methods, you are welcome to share them to communicate and learn together. Thank you!


The above is the detailed content of N algorithms for Fibonacci sequence in PHP. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use Fibonacci sequence algorithm in C++ How to use Fibonacci sequence algorithm in C++ Sep 19, 2023 am 10:15 AM

How to use the Fibonacci sequence algorithm in C++ The Fibonacci sequence is a very classic sequence, and its definition is that each number is the sum of the previous two numbers. In computer science, using the C++ programming language to implement the Fibonacci sequence algorithm is a basic and important skill. This article will introduce how to use C++ to write the Fibonacci sequence algorithm and provide specific code examples. 1. Recursive method Recursion is a common method of Fibonacci sequence algorithm. In C++, the Fibonacci sequence algorithm can be implemented concisely using recursion. under

What are the common algorithms in PHP programming? What are the common algorithms in PHP programming? Jun 12, 2023 am 08:30 AM

In PHP programming, algorithms are an integral part. Mastering common algorithms can not only improve code efficiency, but also help with subsequent program design. The following are common algorithms in PHP programming: Sorting algorithm Sorting algorithm refers to arranging a set of data into an ordered sequence according to certain rules. In PHP programming, commonly used sorting algorithms include bubble sort, insertion sort, selection sort, quick sort, etc. Among them, quick sort is the sorting algorithm with the lowest time complexity and is suitable for processing large-scale data. search algorithm search algorithm

How to write an algorithm to solve the Fibonacci sequence in Python? How to write an algorithm to solve the Fibonacci sequence in Python? Sep 19, 2023 am 09:18 AM

How to write an algorithm to solve the Fibonacci sequence in Python? The Fibonacci sequence is a classic sequence defined as follows: the first and second numbers are both 1, and starting from the third number, each number is the sum of the previous two numbers. That is: 1,1,2,3,5,8,13,21,34,... In Python, you can use a loop or recursion to write an algorithm for solving the Fibonacci sequence. The specific implementation of these two methods will be introduced below. Method 1: Use loopsUse loops

Given a number, write a C program to find the Fibonacci Sequence Given a number, write a C program to find the Fibonacci Sequence Sep 02, 2023 pm 11:49 PM

The Fibonacci sequence is a series of numbers obtained by adding the first two numbers. The Fibonacci sequence starts with two numbers f0 and f1. The initial values ​​of fo and f1 can be 0, 1 or 1, 1. Fibonacci sequence satisfies the following conditions: fn=fn-1+fn-2 algorithm refers to the algorithm of Fibonacci sequence. STARTStep1:Readintegervariablea,b,catruntimeStep2:Initializea=0andb=0Step3:Computec=a+bStep4:PrintcStep5:Seta=b,b=cStep6:Repeat3to5fornt

Array sorting and search algorithm in PHP Array sorting and search algorithm in PHP Jun 23, 2023 am 09:45 AM

PHP is a very popular programming language that supports various data types and algorithms, of which array sorting and search algorithms are basic and important parts. This article will introduce commonly used array sorting and search algorithms in PHP, as well as their application scenarios and efficiency analysis. 1. Array sorting PHP provides a variety of array sorting methods, including bubble sort, insertion sort, selection sort, quick sort, merge sort, etc. The following is an introduction and sample code for several commonly used algorithms: Bubble Sort (BubbleSort)

How to represent knowledge and automatically generate algorithms in PHP? How to represent knowledge and automatically generate algorithms in PHP? May 22, 2023 pm 08:10 PM

With the popularity of the Internet and the continuous expansion of applications, the development of programming languages ​​has become increasingly important. As a very popular programming language, PHP is also constantly developing. In the process of programming with PHP, PHP developers may face the need to represent some knowledge and automatically generate algorithms. So, how to represent knowledge and automatically generate algorithms in PHP? This article will discuss this below. 1. Knowledge representation Knowledge representation is a very important issue in the field of artificial intelligence. Know

PHP algorithm analysis: How to use binary search algorithm to quickly locate elements in an ordered array? PHP algorithm analysis: How to use binary search algorithm to quickly locate elements in an ordered array? Sep 19, 2023 pm 01:14 PM

PHP algorithm analysis: How to use binary search algorithm to quickly locate elements in an ordered array? Overview: The binary search algorithm is an efficient search algorithm that is suitable for finding specific elements in an ordered array. This article will introduce the principle of binary search algorithm in detail and give PHP code examples. Principle: The binary search algorithm quickly locates the target element by repeatedly reducing the search range by half. The process is as follows: first, narrow the search range to the beginning and end of the array; then, calculate the index of the middle element and compare it with the target element;

In-depth understanding of the core algorithms of PHP and Vue in the brain mapping function In-depth understanding of the core algorithms of PHP and Vue in the brain mapping function Aug 15, 2023 pm 01:00 PM

In-depth understanding of the core algorithms of PHP and Vue in the brain mapping function Introduction: In the modern Internet era, we often use a variety of applications to help us organize and manage information. Brain mapping is a common and practical way of organizing information, which can graphically display complex thinking processes. In this article, we will focus on the core algorithms of PHP and Vue in the brain mapping function and give code examples. 1. Characteristics of mind maps. Mind maps are a type of brain map that takes a central theme as its core and displays information related to that theme through a tree structure.

See all articles