def mod_until_one(a, m)
  dot = -1
  count = 0
  while dot != 1
    dot = 1 if dot == -1
    dot = (a * dot) % m
    count += 1
  end
  count
end

def electro_fly(fly_data)
  count1, count2, count3 = (0..4).step(2).map{ |i| fly_data[i,2] }.map{ |d| mod_until_one(*d) }
  count1.lcm count2.lcm count3
end

loop do
  fly_data = gets.chomp.split.map(&:to_i)
  break if fly_data.all?(&:zero?)
  puts electro_fly(fly_data)
end