public static void Solve() { var T = Scanner.Scan <int>(); const long inf = long.MaxValue; while (T-- > 0) { var(X, Y, P, Q) = Scanner.Scan <long, long, long, long>(); var a = X * 2 + Y * 2; var b = P + Q; var answer = inf; for (var t1 = X; t1 < X + Y; t1++) { for (var t2 = P; t2 < P + Q; t2++) { var(t, lcm) = Mathematics.ChineseRemainderTheorem(new[] { t1, t2 }, new[] { a, b }); if (lcm == 0) { continue; } answer = Math.Min(answer, t); } } Console.WriteLine(answer == inf ? "infinity" : $"{answer}"); } }
public void ChineseRemainderTheoremInvalidArgumentsTest() { Assert.Throws <ArgumentException>(() => Mathematics.ChineseRemainderTheorem(new long[] { 1, 2 }, new long[] { 3 })); Assert.Throws <ArgumentException>(() => Mathematics.ChineseRemainderTheorem(new long[] { 1, 2 }, new long[] { -1, -2 })); }
public void ChineseRemainderTheorem2ItemsTest() { for (var a = 1; a <= 20; a++) { for (var b = 1; b <= 20; b++) { for (var c = -10; c <= 10; c++) { for (var d = -10; d <= 10; d++) { var(rem, mod) = Mathematics.ChineseRemainderTheorem(new long[] { c, d }, new long[] { a, b }); var lcm = a * b / GreatestCommonDivisor(a, b); if (mod == 0) { for (var x = 0; x < lcm; x++) { Assert.That(x % a != c || x % b != d, Is.True); } continue; } Assert.That(mod, Is.EqualTo(lcm)); Assert.That(rem % a, Is.EqualTo(Mathematics.SafeModulo(c, a))); Assert.That(rem % b, Is.EqualTo(Mathematics.SafeModulo(d, b))); } } } } }
public override long Part2Long() { long i = 0; Dictionary <long, long> bus = new Dictionary <long, long>(); foreach (var id in parser.Lines[1].Split(',')) { if (id.Equals("x") == false) { try { bus.Add(i, long.Parse(id)); } catch { // nope } } i++; } long result = Mathematics.ChineseRemainderTheorem(bus.Values.ToArray(), bus.Keys.ToArray()); return(result); }
public void ChineseRemainderTheorem3ItemsTest() { for (var a = 1; a <= 5; a++) { for (var b = 1; b <= 5; b++) { for (var c = 1; c <= 5; c++) { for (var d = -5; d <= 5; d++) { for (var e = -5; e <= 5; e++) { for (var f = -5; f <= 5; f++) { var(rem, mod) = Mathematics.ChineseRemainderTheorem(new long[] { d, e, f }, new long[] { a, b, c }); var lcm = a * b / GreatestCommonDivisor(a, b); lcm *= c / GreatestCommonDivisor(lcm, c); if (mod == 0) { for (var x = 0; x < lcm; x++) { Assert.That(x % a != d || x % b != e || x % c != f, Is.True); } continue; } Assert.That(mod, Is.EqualTo(lcm)); Assert.That(rem % a, Is.EqualTo(Mathematics.SafeModulo(d, a))); Assert.That(rem % b, Is.EqualTo(Mathematics.SafeModulo(e, b))); Assert.That(rem % c, Is.EqualTo(Mathematics.SafeModulo(f, c))); } } } } } } }
public void ChineseRemainderTheoremHandmadeTest() { var(rem, mod) = Mathematics.ChineseRemainderTheorem(new long[] { 1, 2, 1 }, new long[] { 2, 3, 2 }); Assert.That(rem, Is.EqualTo(5)); Assert.That(mod, Is.EqualTo(6)); }