Created
June 18, 2011 21:40
-
-
Save finsterthecat/1033531 to your computer and use it in GitHub Desktop.
Euler Problem #3 in Ruby - Find largest prime factor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def big_prime(x) | |
prime = x | |
(2..Math.sqrt(x).to_i).each do |i| | |
break if prime <= i | |
prime /= i while (prime > i && prime % i == 0) | |
end | |
prime | |
end | |
s = Time.new | |
puts big_prime(600851475143) | |
puts "elapsed: #{Time.new-s}" |
Interesting. This takes longest for prime numbers. Methinks this may have applicability in encryption algorithms...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A little slower but now works for even numbers too. Could be optimized further but would violate the first rule of optimization.