euler/ruby/euler044.rb

34 lines
597 B
Ruby

def pentagonal?(n)
((Math.sqrt((24 * n) + 1) + 1) / 6) % 1 == 0
end
def nth_pentagonal(n)
n * (3 * n - 1) / 2
end
def pentagonal
pentagonal_enum = Enumerator.new do |y|
n = 1
loop do
x = n * (3 * n - 1) / 2
n += 1
y << x
end
end
pentagonal_enum
end
def sum_and_difference_pentagonal_up_to(n)
x_list = pentagonal.take_while { |x| x < n }
y_list = pentagonal.take_while { |y| y < n }
solutions = []
x_list.each do |x|
y_list.each do |y|
solutions << [x,y] if pentagonal?(x + y) && pentagonal?((x - y).abs)
end
end
solutions
end