Created
June 28, 2011 05:43
-
-
Save gnarmis/1050563 to your computer and use it in GitHub Desktop.
Finding the Largest Prime Factor of a Composite Number
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 maxPrimeFactor(n) #=> maxPrimeFactor(600851475143) => 6857 in 2007.562 ms | |
# limit the ridiculous range safely | |
range = n**(1/Math.sqrt(n.to_s.length).floor.to_f) | |
ary = (1..range).to_a | |
# Sieve of Eratosthenes (replace with Sieve of Atkin?) | |
for i in ary | |
for j in ary | |
if i != j | |
if (j % i == 0) | |
ary.delete(j) | |
end | |
end | |
end | |
end | |
#remove non-factor primes | |
ary.delete_if{|k| ( n % k != 0)} | |
ary.max | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment