Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to realize n-factorial in php

Shulou Source: shulou.com Published: 2022-05-31 10:58:37 09月17日 Update

This article mainly explains "how to achieve n-factorial in php". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to achieve n-factorial in php".

1. General recursive implementation, it is easy to write the factorial calculation code according to the recursive general formula fact (n) = n * fact (nMel 1).

The advantage of ordinary recursive implementation is that the code is relatively simple, and the same process as the general formula makes the code easy to understand. The disadvantage is that due to the need to call themselves frequently, need a large number of stack operations, the overall computational efficiency is not high.

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

2. The ordinary loop implementation has the flavor of dynamic programming, but due to the low frequency of intermediate state variables, no additional storage space is needed.

Therefore, it is simpler than the general dynamic programming algorithm. The ordinary recursive method is calculated from the top down (from n to 1), while the ordinary loop is calculated from the bottom up.

Function fact (int $n): int {$result = 1; $num = 1; while ($num

Tags: Factorial ordinary recursive code learning formulas content dynamics processes loops planning simplicity frequency top-down advantages variables taste that is ideas situations Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Redmi Docker Apple Shulou Technology