In this article, the author discusses a fast and accurate method to calculate the factorial of a large number using fixed-point bignumber library. A recurring question about the implementation was the extraction of the T2 term from the product T1 = T2 * N!, where T1 and N! are already known. To find the T2 term, the author conducted an analysis on prime exponents and proposed a formula to calculate it:
T2(4N) = multiplication(i=all primes<=4N) of [i^sum(j=1,2,3,4,5,...4N/(i^j)) of [(4N/(i^j))%2]]
Subterms of T2 have exponent e for prime i inside the T2(N) term that can be computed like this:
for (e=0,j=N4;j;e+=j&1,j/=p);
where e is exponent, p is prime and N4 is 4*N
The computed T2 term is then used to optimize the computation of factorials, and the resulting algorithm exhibits a computational complexity near ~ O(log(n)).
Rough time measurements are provided for the first 128 factorials. The author acknowledges that this implementation cannot be simplified further and is already highly optimized.
The above is the detailed content of How Can We Efficiently Extract the T2 Term from T1 = T2 * N! Using Prime Exponent Analysis?. For more information, please follow other related articles on the PHP Chinese website!