結果

問題 No.1936 Rational Approximation
ユーザー lam6er
提出日時 2025-03-20 20:46:23
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 36 ms / 2,000 ms
コード長 701 bytes
コンパイル時間 144 ms
コンパイル使用メモリ 82,352 KB
実行使用メモリ 53,380 KB
最終ジャッジ日時 2025-03-20 20:46:25
合計ジャッジ時間 1,413 ms
ジャッジサーバーID
(参考情報)
judge4 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 14
権限があれば一括ダウンロードができます

ソースコード

diff #

def extended_gcd(a, b):
    if b == 0:
        return (a, 1, 0)
    else:
        g, x, y = extended_gcd(b, a % b)
        return (g, y, x - (a // b) * y)

def modinv(a, m):
    g, x, y = extended_gcd(a, m)
    if g != 1:
        return None  # This should not happen as per problem constraints
    else:
        return x % m

# Read input
P, Q = map(int, input().split())

# Compute inverse of P modulo Q
inv_p = modinv(P, Q)

# Calculate left fraction (a_left / b_left)
b_left = inv_p
a_left = (b_left * P - 1) // Q

# Calculate right fraction (c_right / d_right)
d_right = (-inv_p) % Q
c_right = (d_right * P + 1) // Q

# Sum all components
total = a_left + b_left + c_right + d_right

print(total)
0