Calculating phi(k) for 1<k<N

前端 未结 9 1875
花落未央
花落未央 2020-12-04 20:08

Given a large N, I need to iterate through all phi(k) such that 1 < k < N :

  • time-complexity must be O(N logN)
  • memory-complexity mus
9条回答
  •  囚心锁ツ
    2020-12-04 21:08

    This factorizes N = PQ, where P & Q are prime.

    Works quite well, in Elixir or Erlang.

    You can try different generators for your pseudo-random sequence. x*x + 1 is commonly used.

    This line: defp f0(x, n), do: rem((x * x) + 1, n)

    Other possible points of improvement: better or alternative gcd, rem and abs functions

    defmodule Factorizer do
    
      def factorize(n) do
        t = System.system_time
    
        x = pollard(n, 2_000_000, 2_000_000)
        y = div(n, x)
        p = min(x, y)
        q = max(x, y)
    
        t = System.system_time - t
    
        IO.puts "
    Factorized #{n}: into [#{p} , #{q}] in #{t} μs
    "
    
        {p, q}
      end
    
      defp gcd(a,0), do: a
      defp gcd(a,b), do: gcd(b,rem(a,b))
    
      defp pollard(n, a, b) do
        a = f0(a, n)
        b = f0(f0(b, n), n)
    
        p = gcd(abs(b - a), n)
    
        case p > 1 do
          true  -> p
          false -> pollard(n, a, b)
        end
      end
    
      defp f0(x, n), do: rem((x * x) + 1, n)
    
    end
    

提交回复
热议问题