search
HomeBackend DevelopmentPHP ProblemHow to implement the factorial of n in php

php method to implement the factorial of n: 1. Implement it through ordinary recursion, with code such as "function fact(int $n): int{...}"; 2. Implement it with ordinary loops, with code such as " while ($num

How to implement the factorial of n in php

The operating environment of this article: Windows 10 system, PHP version 7.2.15, DELL G3 computer

How does php realize the factorial of n?

As far as I know, the implementation methods of factorial can generally be divided into three types. Recursion and looping in the usual sense are each considered one type, and there is also a large category that uses some clever mathematical methods to reduce the number of operations ( Especially the number of multiplication operations), thereby optimizing computing efficiency.

If you want to consider the factorial of high-precision, large integers, the situation will be more complicated for the PHP language. For example, when using some methods provided by the BCMath extension, explicit number and string conversion operations are compared. frequently.

This article only considers n as an integer, and attempts to implement the above situations respectively. Available code examples are given in each case, and a comprehensive comparison of several methods is attached at the end of the article.

Ordinary recursive implementation

The first is the ordinary recursive implementation. According to the general recursive formula fact(n) = n * fact(n-1), it is easy to write the factorial calculation code. The advantage of ordinary recursive implementation is that the code is relatively concise, and the same process as the general formula makes the code easy to understand. The disadvantage is that because it needs to call itself frequently, a large number of push and pop operations are required, and the overall calculation efficiency is not high (see the table at the end of the article).

function fact(int $n): int
{
    if ($n == 0) {
        return 1;
    }
    return $n * fact($n - 1);
}

Ordinary loop implementation

Ordinary loop implementation has the flavor of "dynamic programming", but due to the low frequency of use of intermediate state variables, no additional storage space is required, so It is simpler than the general dynamic programming algorithm. The ordinary recursive method is a top-down (from n to 1) calculation process, while the ordinary loop is a bottom-up calculation.

Therefore, relatively speaking, the code is not as intuitive as the above method, but due to the lack of frequent push and pop processes, the calculation efficiency will be higher (see the table at the end of the article).

function fact(int $n): int
{
    $result = 1;
    $num = 1;
    while ($num <= $n) {
        $result = $result * $num;
        $num = $num + 1;
    }
    return $result;
}

Self-implemented large integer factorial

Due to the range limitation of the int type in PHP, the above two methods can only accurately calculate factorials up to 20. If you only consider the factorial of 20, it will be faster to use the lookup table method: calculate the factorial of 0-20 in advance and store it in an array, and query it once when needed.

In order to be able to adapt to the factorial of large numbers and obtain accurate calculation results, this article is improved based on the "ordinary loop method", using an array to store each bit in the calculation result (from low to high), and multiplying The carry method calculates the result of each bit in turn.

It goes without saying that the advantage of this method is that it can be applied to high-precision large number factorial situations. The disadvantage is that for decimal factorials, the calculation process is complicated and slow.

function fact(int $n): array
{
    $result = [1];
    $num = 1;
    while ($num <= $n) {
        $carry = 0;
        for ($index = 0; $index < count($result); $index++) {
            $tmp = $result[$index] * $num + $carry;
            $result[$index] = $tmp % 10;
            $carry = floor($tmp / 10);
        }
        while ($carry > 0) {
            $result[] = $carry % 10;
            $carry = floor($carry / 10);
        }
        $num = $num + 1;
    }
    return $result;
}

BCMath Extension Method

BCMath is a mathematical extension for PHP that handles numerical computations on numbers (of any size and precision) represented by strings. Since it is an extension implemented in C language, the calculation speed will be faster than the above self-implementation.

Recommended study: "PHP Video Tutorial"

On my laptop, I also calculate the factorial of 2000. It takes an average of 0.5-0.6 seconds to implement it by myself. Use BCMath takes 0.18-0.19 seconds. The main disadvantage of this method is that it requires the installation of corresponding extensions, which is a non-code level change. For applications where environmental management upgrades are inconvenient, the practicality is questionable.

function fact(int $n): string
{
    $result = &#39;1&#39;;
    $num = &#39;1&#39;;
    while ($num <= $n) {
        $result = bcmul($result, $num);
        $num = bcadd($num, &#39;1&#39;);
    }
    return $result;
}

Optimization Algorithm

As mentioned at the beginning of this article, the optimization algorithm tries to reduce the number of operations (especially the number of multiplication operations) as much as possible to achieve fast factorial. Considering that for small integer factorials, the fastest algorithm should be the table lookup method, with a time complexity of O(1), so this section mainly discusses and tests the exact factorial of large integers.

It is understood that factorial optimization is currently more common through n! = C(n, n/2) * (n/2)! * (n/2)! Complexity optimization, and The highlight of this formula mainly lies in the optimization of C(n, n/2). Considering that in the case of large integers, the efficiency of the PHP language to implement C(n, n/2) is not high, and the code readability is relatively poor (frequent explicit conversion of numbers and strings), so this article uses Another more clever method.

The calculation speed of multiplication is usually lower than that of addition and subtraction. By reducing the number of multiplication operations, the overall calculation speed can be improved. Through mathematical induction, we can find that for the factorial of n, we can successively find values ​​that are 1, 1 3, 1 3 5... smaller than (n/2)^2, and then multiply them in sequence to obtain the target value.

The advantage of this algorithm is that the calculation speed is fast, but the disadvantage is that the implementation process is not intuitive and difficult to understand. After testing, the following code calculates the factorial average time of 2000 to 0.11 seconds, which is about half the time of the ordinary loop method.

In addition to this method of optimization, we have also seen other similar ideas, such as repeatedly checking whether the numbers in 1...n are divisible by 2, recording the number of times divisible by 2 x, and trying to generalize Find the common odd number multiplication formula, and finally multiply it by 2^x to get the result.

function fact(int $n): string
{
    $middleSquare = pow(floor($n / 2), 2);
    $result = $n & 1 == 1 ? 2 * $middleSquare * $n : 2 * $middleSquare;
    $result = (string)$result;
    for ($num = 1; $num < $n - 2; $num = $num + 2) {
        $middleSquare = $middleSquare - $num;
        $result = bcmul($result, (string)$middleSquare);
    }
    return $result;
}

综合对比

本文中提到的方法是按照由劣到优的顺序,因此,下列表格中每一行中提到优劣势,主要是和其上一两种方法对比。

表格中「测试耗时」一列的测试环境为个人笔记本,硬件配置为 Dell/i5-8250U/16GB RAM/256GB SSD Disk,软件配置为 Win 10/PHP 7.2.15。

How to implement the factorial of n in php

总结

虽然本文将实现方法分为三大类,但其实也可以分为循环和递归两大类,在这两类中分别使用相应的算法优化计算效率。But,总体而言,循环的效率要优于递归。

讲道理,本文中使用的优化算法并不是最优解,只是用 PHP 相对好实现,代码易读性也比较高。有兴趣的读者可以谷歌了解更多的骚操作。

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

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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),