Brute-force, single-threaded prime factorization

前端 未结 7 689
误落风尘
误落风尘 2020-12-07 22:08

Up for consideration is the following function which can be used to (relatively quickly) factor a 64-bit unsigned integer into its prime factors. Note that the factoring is

7条回答
  •  忘掉有多难
    2020-12-07 22:30

    Fermat's factorization method is simple and quick for finding pairs of large prime factors as long as you stop it before it goes too far and becomes slow. However, in my tests on random numbers such cases have been too rare to see any improvement.

    ...without using a probabalistic approach (e.g., Miller-Rabin) for determining primality

    With uniform distribution, 75% of your inputs are going to need a billion loop iterations, so it's worth spending a million operations on less deterministic techniques first even if you get an inconclusive answer and have to revert back to trial division.

    I've found the Brent variation of Pollard's Rho Method to be very good, though more complicated to code and understand. The best example I've seen is from this forum discussion. The method relies on luck, but helps often enough to be worthwhile.

    The Miller-Rabin primality test is actually deterministic up to about 10^15, which can save you the trouble of a fruitless search.

    I tried a few dozen variations and settled on the following for factoring int64 values:

    1. Trial division on small factors. (I use first 8000 precomputed primes.)
    2. 10 attempts with Pollard's Rho, each using 16 iterations
    3. Trial division to sqrt(n).

    Note that Pollard's Rho finds factors that are not necessarily prime, so recursion can be used to factor those.

提交回复
热议问题