How can I speed up this Julia code?

The code implements an example of the Pollard function rho () to find the factor of a natural number n. I learned some of the code in the Julia "Primes" package, which runs quickly to speed up the pollard_rho () function, but to no avail. The code should execute n = 1524157897241274137 approximately in the range from 100 ms to 30 seconds (Erlang, Haskell, Mercury, SWI Prolog), but takes 3 to 4 minutes on JuliaBox, IJulia and Julia REPL. How can i do this fast?

pollard_rho (1524157897241274137) = 1234567891

__precompile__()
module Pollard

export pollard_rho

function pollard_rho{T<:Integer}(n::T)
    f(x::T, r::T, n) = rem(((x ^ T(2)) + r), n)
    r::T = 7; x::T = 2; y::T = 11; y1::T = 11; z::T = 1
    while z == 1
        x  = f(x, r, n)
        y1 = f(y, r, n)
        y  = f(y1, r, n)
        z  = gcd(n, abs(x - y))
    end
    z >= n ? "error" : z
end

end # module
+4
source share
1 answer

There are many problems with type instability.

  • "error" ; error().

  • , x r T, .

. , T.

function pollard_rho{T<:Integer}(n::T)
    f(x::T, r::T, n) = rem(Base.widemul(x, x) + r, n) % T
    r::T = 7; x::T = 2; y::T = 11; y1::T = 11; z::T = 1
    while z == 1
        x  = f(x, r, n)
        y1 = f(y, r, n)
        y  = f(y1, r, n)
        z  = gcd(n, abs(x - y))
    end
    z >= n ? error() : z
end

, .

julia> @btime pollard_rho(1524157897241274137)
  4.128 ms (0 allocations: 0 bytes)
1234567891

, @code_warntype.

+12

Source: https://habr.com/ru/post/1674125/


All Articles