Created
July 1, 2012 22:35
-
-
Save pjc/3029870 to your computer and use it in GitHub Desktop.
Euler Project in Ruby - Problem 3
This file contains 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
# We make array of prime numbers with modulus 0 as long as product_sum < n | |
def prime? n | |
(2..(n-1)).each { |x| return false if n % x == 0 } | |
true | |
end | |
n = 600_851_475_143 | |
a = [] | |
product_sum = 1 | |
x = 2 # 2 is the first prime number | |
while product_sum < n | |
if n % x == 0 && prime?(x) | |
a << x | |
product_sum *= x | |
end | |
x += 1 | |
end | |
puts "The answer is #{a.last}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I started working on this yesterday and though I arrived at a solution that worked quickly for numbers up to 7 digits. I cried "uncle" and looked a this solution. Although previous commenter dolomite pointed out a flaw in the posted solution, this solution still helped me to refine my attempt. Here it is:
class PrimeFactorGenerator
end
g = PrimeFactorGenerator.new(600851475143)
g.greatest_prime_factor # => 6857
Tested with smaller number that have redundant factors (24 = 2_2_2*3) and works for those too.