Skip to content

Instantly share code, notes, and snippets.

@xymor
Last active December 14, 2015 04:08
Show Gist options
  • Save xymor/5025721 to your computer and use it in GitHub Desktop.
Save xymor/5025721 to your computer and use it in GitHub Desktop.
Ruby Euler #3
#print the largest prime factor a number
#this is the most elegant way and work ok for large numbers
require 'prime'
Prime.prime_division(big_number).max()
# Not using Prime which has pretty bad performance before 1.9
# and using tail recursion which is cool as fast
number = ARGV.first.to_i
def generate(n, largest = 1)
return largest if n == 1
new_factor = (2..n).find {|f| n % f == 0}
generate(n / new_factor, new_factor)
end
factor = generate(number)
puts "Largest factor of #{number} is #{factor}"
# This one is for really big numbers 100+ digits
# That Sqrt theorem is very interesting, I don't fully get the math but I believe the PhDs :D
# http://math.stackexchange.com/questions/102755/greatest-prime-factor-of-n-is-less-than-square-root-of-n-proof/102760#102760
# in my tests the performance is much worst than the native ruby Prime class
# the idea from the regexp prime checker comes from here https://github.com/fxn/math-with-regexps/blob/master/one-liners.sh
number = "10000000000"
def isPrimeRegexp n
"1" * n =~ /^1?$|^(11+?)\1+$/
end
Math.sqrt(number).to_i.downto(2) do |n|
if isPrimeRegexp(n) && number%n ==0
puts "Largest factor of #{number} is #{n}"
break
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment