Skip to content

Instantly share code, notes, and snippets.

@gnarmis
Created June 28, 2011 05:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gnarmis/1050563 to your computer and use it in GitHub Desktop.
Save gnarmis/1050563 to your computer and use it in GitHub Desktop.
Finding the Largest Prime Factor of a Composite Number
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