結果

問題 No.186 中華風 (Easy)
ユーザー Takahiro INOUETakahiro INOUE
提出日時 2019-06-04 10:47:02
言語 Python3
(3.11.6 + numpy 1.26.0 + scipy 1.11.3)
結果
AC  
実行時間 21 ms / 2,000 ms
コード長 1,259 bytes
コンパイル時間 784 ms
コンパイル使用メモリ 10,940 KB
実行使用メモリ 8,812 KB
最終ジャッジ日時 2023-09-27 00:55:40
合計ジャッジ時間 1,899 ms
ジャッジサーバーID
(参考情報)
judge15 / judge12
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 20 ms
8,640 KB
testcase_01 AC 19 ms
8,628 KB
testcase_02 AC 18 ms
8,780 KB
testcase_03 AC 19 ms
8,700 KB
testcase_04 AC 19 ms
8,652 KB
testcase_05 AC 18 ms
8,756 KB
testcase_06 AC 19 ms
8,764 KB
testcase_07 AC 21 ms
8,680 KB
testcase_08 AC 19 ms
8,776 KB
testcase_09 AC 19 ms
8,812 KB
testcase_10 AC 19 ms
8,764 KB
testcase_11 AC 20 ms
8,696 KB
testcase_12 AC 20 ms
8,624 KB
testcase_13 AC 20 ms
8,692 KB
testcase_14 AC 19 ms
8,764 KB
testcase_15 AC 19 ms
8,812 KB
testcase_16 AC 19 ms
8,776 KB
testcase_17 AC 20 ms
8,812 KB
testcase_18 AC 19 ms
8,764 KB
testcase_19 AC 19 ms
8,636 KB
testcase_20 AC 19 ms
8,772 KB
testcase_21 AC 21 ms
8,688 KB
testcase_22 AC 20 ms
8,796 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from functools import reduce

def gcd(a, b):
    while b:
        a, b = b, a%b
    return a

def lcm(a, b):
	return a * b // gcd (a, b)

def extended_euclid(a, b):
    x1, y1, m = 1, 0, a
    x2, y2, n = 0, 1, b
    while m % n != 0:
        q, r = divmod(m, n)
        x1, y1, m, x2, y2, n = x2, y2, n, x1 - q * x2, y1 - q * y2, r
    return (x2, y2, n)

def chinese_reminder(A, M):
    '''
        solve
            x \equiv a_1 (mod m_1), ... x \equiv a_k (mod m_k)
        by applying the Chinese reminder theorem
        Input: 
            A = [a_1, ..., a_k]: a list
            M = [m_1, ..., m_k]: a list.
        Output:
            Returns the tuple (x, mod) of the solution x and the modulus mod = m_1 ... m_k if exists
            else (0, -1).
    '''
    # initialize
    x = 0
    mod = 1
    for a, m in zip(A, M):
        u, v, g = extended_euclid(mod, m)
        q, r = divmod(a - x, g)
        if r != 0:
            return (0, -1)
        x += q * mod * u
        mod *= m // g
        x %= mod
    return (x, mod)

A = []
M = []
for _ in range(3):
    a, m = map(int, input().split())
    A.append(a)
    M.append(m)
x, m = chinese_reminder(A, M)
if (x, m) == (0, -1):
    x = -1
elif x == 0 and m != -1:
    x = reduce(lcm, M)
print(x)
0