Skip to content

Instantly share code, notes, and snippets.

@kou1okada
Last active October 18, 2024 09:24
Show Gist options
  • Save kou1okada/d3f3cab7b9eb32755e4a6e41cd01b84f to your computer and use it in GitHub Desktop.
Save kou1okada/d3f3cab7b9eb32755e4a6e41cd01b84f to your computer and use it in GitHub Desktop.
Pollard's rho algorithm

Pollard's rho algorithm

Original Papers

Pollard's rho algorithm

An improvement by Richard P. Brent

Other References

#!/usr/bin/env ruby
# Pollard's rho algorithm
# @reference
# * [ポラード・ロー素因数分解法](https://ja.wikipedia.org/wiki/%E3%83%9D%E3%83%A9%E3%83%BC%E3%83%89%E3%83%BB%E3%83%AD%E3%83%BC%E7%B4%A0%E5%9B%A0%E6%95%B0%E5%88%86%E8%A7%A3%E6%B3%95)
# * [素因数分解の高速なアルゴリズム(ロー法)](http://mathtrain.jp/rhoalgorithm)
def pollards_rho_algorithm(n)
f = -> x { (x * x + 1) % n }
x = 2
y = 2
d = 1
while d == 1
x = f.call(x)
y = f.call(f.call(y))
d = (x-y).abs.gcd(n)
end
d == n ? nil : d
end
puts pollards_rho_algorithm ARGV[0].to_i if File.expand_path($0) == File.expand_path(__FILE__)
#!/usr/bin/env ruby
# Richard P.Brent algorithm
# @reference
# * [ポラード・ロー素因数分解法](https://ja.wikipedia.org/wiki/%E3%83%9D%E3%83%A9%E3%83%BC%E3%83%89%E3%83%BB%E3%83%AD%E3%83%BC%E7%B4%A0%E5%9B%A0%E6%95%B0%E5%88%86%E8%A7%A3%E6%B3%95)
# * [RICHARD P.BRENT, AN IMPROVED MONTE CARLO FACTORIZATION ALGORITHM](http://web.comlab.ox.ac.uk/oucl/work/richard.brent/pd/rpb051i.pdf)
def richard_p_brent_algorithm(n)
f = -> x { (x * x + 3) % n }
x0 = 0
m = 1
y = x0
r = 1
q = 1
begin
x = y
r.times{ y = f.call(y) }
k = 0
begin
ys = y
[m, r - k].min.times{
y = f.call(y)
q = (q * (x - y).abs) % n
}
g = q.gcd(n)
k += m
end until k >= r || g > 1
r *= 2
end until g > 1
if (g == n)
begin
ys = f.call(ys)
g = (x - ys).abs.gcd(n)
end until g > 1
end
g == n ? nil : g
end
puts richard_p_brent_algorithm ARGV[0].to_i if File.expand_path($0) == File.expand_path(__FILE__)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment