solution_comparison/chain_fraction.py

53 lines
1.3 KiB
Python
Raw Normal View History

2025-01-09 01:45:09 +03:00
import re, sys
def gcd(a, b):
while b != 0:
b, a = a % b, b
return a
def get_q_list(m, a):
l = []
while a:
r, q = m % a, m // a
m, a = a, r
l.append(q)
return l
def get_p_n(n, q_list):
if n == 0:
return q_list[0]
if n == 1:
return q_list[0] * q_list[1] + 1
return q_list[n] * get_p_n(n - 1, q_list) + get_p_n(n - 2, q_list)
def get_x0(a, b, m):
q_list = get_q_list(m, a)
n = len(q_list) - 1
p = get_p_n(n-1, q_list)
x = ((-1)**n*p*b)%m
return x, f'x={x}mod{m}'
def solve(task):
f = re.fullmatch(r'(\d+)x=(\d+)mod(\d+)', task)
if f == None:
return "Usage Example: py chain_fraction.py '7x=8mod13'"
a, b, m = int(f.groups()[0]), int(f.groups()[1]), int(f.groups()[2])
d = gcd(a, m) # Находим НОД
if d == 1: # нод = 1 => 1 решение
return get_x0(a, b, m)[1]
if d > 1 and b % d != 0:
return 'No solutions'
else:
d = gcd(gcd(a, b), m)
a1, b1, m1 = a // d, b // d, m // d
x0 = get_x0(a1, b1, m1)[0]
s = ""
for k in range(d):
s += f'x={(x0+m1*k)%m}mod{m}\n'
return s[:-1]
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage Example: py chain_fraction.py '7x=8mod13'")
sys.exit(1)
print(solve(sys.argv[1]))