def extgcd(a, b) if b.zero? {x: 1, y: 0, gcd: a} else prev = extgcd(b, a % b) { x: prev[:y], y: prev[:x] - (a / b) * prev[:y], gcd: prev[:gcd] } end end def mod_inv(a,m) res = extgcd(a,m) x = res[:x] return (m+x%m)%m end def lc(a,b,m) xx,mm = 0,1 a.size.times do |i| aa = a[i]*mm bb = b[i] - a[i] * xx dd = m[i].gcd(aa) return if bb % dd != 0 tt = bb/dd * mod_inv(aa/dd, m[i]/dd) % (m[i] / dd) xx = xx + mm*tt mm *= m[i]/dd end return [xx%mm,mm] end n = 3 xs, ys = [], [] n.times do x,y = gets.chomp.split.map(&:to_i) xs << x ys << y end as = [1] * n ans = lc(as,xs,ys) puts ans.nil? ? -1 : (ans[0] == 0 ? ans[1] : ans[0])