long[] ext_gcd(long a, long b) { if (b == 0) { return [1, 0, a]; } else { auto xyg = ext_gcd(b, a % b); return [xyg[1], xyg[0] - a / b * xyg[1], xyg[2]]; } } long chi_rem(long[] a, long[] m) { assert(a.length == m.length); long res = 0, M = 1; foreach (i; 0 .. a.length) { auto xyg = ext_gcd(M, m[i]); if ((a[i] - res) % xyg[2] != 0) { return -1; } res += (a[i] - res) / xyg[2] * xyg[0] * M; M *= m[i] / xyg[2]; } return (res % M + M) % M; } void main() { import std.stdio, std.string, std.conv, std.algorithm; import std.numeric; auto x = new long[](3), y = new long[](3); rd(x[0], y[0]); rd(x[1], y[1]); rd(x[2], y[2]); if (reduce!"a+b"(x) == 0) { auto g = gcd(y[0], y[1]); auto l = y[0] * y[1] / g; g = gcd(l, y[2]); writeln(l * y[2] / g); return; } writeln(chi_rem(x, y)); } void rd(T...)(ref T x) { import std.stdio : readln; import std.string : split; import std.conv : to; auto l = readln.split; assert(l.length == x.length); foreach (i, ref e; x) e = l[i].to!(typeof(e)); }