Get the App
SLTechnology News&Howtos  ›  Development  › 

Factorial related algorithms and example Analysis of their C++ implementation

Shulou Source: shulou.com Published: 2022-06-02 11:29:19 10月06日 Update

This article shows you the factorial-related algorithms and their C++ implementation example analysis, the content is concise and easy to understand, absolutely can make your eyes bright, through the detailed introduction of this article, I hope you can get something.

Factorial means to multiply from 1 times 2 times 3 times 4 to the required number. The same is true of factorials in C++. The algorithm of factorial is nothing more than two aspects: one is high-precision calculation, the other is related to number theory.

one. High precision calculation of factorial

This is actually the least technical problem, but it is often used, so you still have to write and optimize its calculations.

First, look at factorial calculations that are less than or equal to 12 (the results will not exceed the 32-bit range):

Int factorial (int n) {if (n = = 1 | | n = = 0) return 1; return factorial (nmur1) * n;}

This recursive program is simple and intuitive, but once n > 12, there is an error result beyond the range of 32-bit int, so the above recursive program is only suitable for n = m, then m can definitely divide n!

b. Then there is only one case left: M > n, we start with the minimum prime factor of m, set the prime factor to I, then we can get the number of prime factors of m nums1; and check the number of prime factors between the closed interval I ~ n, and then we can simply use the mathematical formula introduced in (2) above to calculate nums2. If nums2

< nums1,就表示1 ~ n中包含素因子的数量 < 除数m包含素因子i的数量,那么m必然不能整除n!,置ok = false。 C. ***:如果 !ok or m >

If n or m = 0, it is not divisible; otherwise, it is divisible.

(5). Can the number N be expressed as the sum of several different factorials:

The factorial that can be chosen here is: 0! ~ 9. In fact, this question has nothing to do with number theory, but has something to do with search. Related topic: 2358 questions of http://acm.zju.edu.cn.

Analysis, due to the small number of factorials available, you can directly use DFS search to do:

a. First, the factorial of 0 ~ 9 is made into a table A [10], and then an array ans [N] that can be composed of "and" is set.

b. Depth first search method:

Search (n) {for (I = n; I)

Tags: Factorial factor algorithm quantity high precision high precision number analysis multiplication that is array end result zero actual number theory last bit title Category number. Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Docker MariaDB NVidia Linux