raise "Expected Filename" unless ARGV[0]
file = File.open(ARGV[0])
input = file
  .readlines
  .map{|line| line.split(',').map{|s| s == 'x' ? 'x' : s.to_i } }
file.close

start_time = input[0][0]

unless ARGV[1] && ARGV[1] == "2"
  result = input[1]
    .select{|route| route != 'x' }
    .map do |route|
      m = start_time % route
      {
        id: route,
        wait: m == 0 ? 0 : route - m,
      }
    end.min{|a, b| a[:wait] <=> b[:wait] }

  puts result[:id] * result[:wait]
else
  result = 0
  factor = 1
  input[1].each_with_index.select{|route,_| route != 'x' }.each do |(route,ix)|
    while (result + ix) % route != 0
      result += factor
    end
    factor = factor.lcm(route)
  end
  puts result
end