Snippets

cia_rana 左と右の有理数

You are viewing an old version of this snippet. View the current version.
Revised by cia_rana a11d27c
def to_right_child x, y
  [y - x, y]
end
def to_left_child x, y
  [x, x + y]
end
def from_right_child x, y
  [y - x, y]
end
def from_left_child x, y
  [x, y - x]
end
def decide_right x, y
  i = 0
  a, b = x, y
  loop do
    return [?-] if a * 2 == b
    c, d = from_left_child(a, b)
    if c > d
      a, b = from_right_child(a, b)
      i += 1
      next
    elsif c * 2 < d
      a, b = to_right_child(c, d)
      break
    else
      a, b = c, d
      i += 1
    end
  end
  [a, a * i + b]
end
def decide_left x, y
  i = 0
  a, b = x, y
  loop do
    return [?-] if a * 2 == b
    c, d = from_left_child(a, b)
    if c > d
      a, b = to_left_child *from_right_child(a, b)
      break
    else
      a, b = c, d
      i += 1
    end
  end
  (0...i).each{ a, b = a * 2 > b ? to_left_child(a, b) : to_right_child(a, b) }
  [a, b]
end

x, y = gets.scan(/\d+/).map(&:to_i)
puts decide_left(x, y)*?/ + ?, + decide_right(x, y)*?/
HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.