Skip to content

Instantly share code, notes, and snippets.

@finsterthecat
Created June 18, 2011 21:40
Show Gist options
  • Save finsterthecat/1033531 to your computer and use it in GitHub Desktop.
Save finsterthecat/1033531 to your computer and use it in GitHub Desktop.
Euler Problem #3 in Ruby - Find largest prime factor
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}"
@finsterthecat
Copy link
Author

A little slower but now works for even numbers too. Could be optimized further but would violate the first rule of optimization.

@finsterthecat
Copy link
Author

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