euler/ruby/euler046.rb

50 lines
821 B
Ruby

require 'prime'
def odd_composites
enum = Enumerator.new do |y|
a = 3
loop do
y << a unless Prime.prime?(a)
a += 2
end
end
enum
end
def squares
enum = Enumerator.new do |y|
n = 1
loop do
y << n ** 2
n += 1
end
end
enum
end
def find_sum(num)
found = false
primes = Prime::EratosthenesGenerator.new
prime = 0
squares_enum = squares
while prime < num
prime = primes.next
squares_enum.rewind
twice_square = squares_enum.next * 2
while twice_square < num
return [prime, twice_square / 2] if twice_square + prime == num
twice_square = squares_enum.next * 2
end
end
found
end
def property?(num)
find_sum(num)
end
def find_incorrect_up_to(n)
odd_composites.take_while { |x| x < n }.reject{ |x| property?(x) }
end