1. 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 computing efficiency is not high.
function fact(int $n): int { if ($n == 0) { return 1; } return $n * fact($n - 1); }
2. Ordinary loop implementation has some 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.
function fact(int $n): int { $result = 1; $num = 1; while ($num <= $n) { $result = $result * $num; $num = $num + 1; } return $result; }
The above is the implementation method of n factorial in php. I hope it will be helpful to everyone.