Kyopro Library
 
読み取り中…
検索中…
一致する文字列を見つけられません
mod_reconstruct.py
[詳解]
1# p/q mod P が与えられたとき、p, q を復元する
2
3def reconstruct(n, mod):
4 v = [mod, 0]
5 w = [n, 1]
6 while w[0] * w[0] * 2 > mod:
7 q = v[0] // w[0]
8 z = [v[0] - q * w[0], v[1] - q * w[1]]
9 v = w
10 w = z
11 print(w)
12
13 if w[1] < 0:
14 w[0] *= -1
15 w[1] *= -1
16
17 return w
18
19def add_rational_expression(original, mod):
20 original += '*'
21 buffer = ""
22 res = ""
23 tag_parsing = False
24
25 for c in original:
26 if c == '<':
27 tag_parsing = True
28 res += buffer
29 buffer = ""
30 elif c == '>':
31 tag_parsing = False
32
33 if not tag_parsing:
34 if '0' <= c <= '9':
35 buffer += c
36 else:
37 if buffer:
38 num = int(buffer)
39 if num < mod and num * num * 2 > mod:
40 w = reconstruct(num, mod)
41 buffer += f' ({w[0]}/{w[1]}) '
42 res += buffer
43 buffer = ""
44 res += c
45 else:
46 res += c
47
48 return res[:-1]
49
50def main():
51 mod = 998244353
52 original = input("Enter the expression: ")
53
54 if mod:
55 result = add_rational_expression(original, mod)
56 print("Result:", result)
57 else:
58 print("No recognized mod value found in the input.")
59
60if __name__ == "__main__":
61 main()
add_rational_expression(original, mod)