Skip to content

Instantly share code, notes, and snippets.

@hjroh0315
Last active December 20, 2022 12:33
Show Gist options
  • Save hjroh0315/47a835e018261c905585ca17e9754998 to your computer and use it in GitHub Desktop.
Save hjroh0315/47a835e018261c905585ca17e9754998 to your computer and use it in GitHub Desktop.
pollard rho in ruby
require'prime'
def pollard_rho(n)
stk=[n]
ans=[]
while stk.size>0 do
cn=stk.pop
#p cn
next if cn==1
if cn%2==0
ans << 2
stk << cn/2
next
end
if cn.prime? # Miller-Rabin based Primality test is implemented on Ruby 3.1.0 and above. Implement it yourself if needed!
ans << cn
next
end
a=-1;b=-1;c=-1;g=cn
loop do
if g==cn
a=rand(cn-2)+2;b=a
c=rand(20)+1
end
a=(a*a+c)%cn
b=(b*b+c)%cn
b=(b*b+c)%cn
g=cn.gcd((a-b).abs)
break if g!=1
end
stk << cn/g
stk << g
end
ans.sort
end
class Integer
def factorize
pollard_rho(self)
end
def prime_division
pollard_rho(self).chunk{|v|v}.map{|v,a|[v,a.size]}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment