first commit

main
serr 2025-01-09 01:45:09 +03:00
commit 8aaaddb9f3
3 changed files with 124 additions and 0 deletions

53
chain_fraction.py Normal file
View File

@ -0,0 +1,53 @@
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]))

31
euclid.py Normal file
View File

@ -0,0 +1,31 @@
import sys, re
def gcd(a, b):
if b == 0:
return 1, 0, a
x, y, d = gcd(b, a % b)
x = y
y = (d - x*a) // b
return x, y, d
def solve(task):
f = re.fullmatch(r'(\d+)x=(\d+)mod(\d+)', task)
if f == None:
return "Usage Example: py euclid.py '7x=8mod13'"
a, b, m = int(f.groups()[0]), int(f.groups()[1]), int(f.groups()[2])
d = gcd(a, m)[2]
if d > 1 and b % d != 0:
return 'No solutions'
a1, b1, m1 = a // d, b // d, m // d
u, _, _ = gcd(a1, m1)
x0 = b1*u
s = ""
for i in range(0, d):
s += f'x={(x0+m//d*i)%m}mod{m}\n'
return s[:-1]
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage Example: py euclid.py '7x=8mod13'")
sys.exit(1)
print(solve(sys.argv[1]))

40
euler.py Normal file
View File

@ -0,0 +1,40 @@
import sys, re
def gcd(a, b):
while b != 0:
b, a = a % b, b
return a
def euler(n):
result = n
p = 2
while p * p <= n:
if n % p == 0:
while n % p == 0:
n //= p
result -= result // p
p += 1
if n > 1:
result -= result // n
return result
def solve(task):
f = re.fullmatch(r'(\d+)x=(\d+)mod(\d+)', task)
if f == None:
return "Usage Example: py euler.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 and b % d != 0:
return 'No solutions'
a1, b1, m1 = a // d, b // d, m // d
x0 = (b1 * pow(a1, euler(m1) - 1, m1)) % m1
s=''
for i in range(d):
s += f"x={(x0 + i * m//d) % m}mod{m}\n"
return s[:-1]
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage Example: py euler.py '7x=8mod13'")
sys.exit(1)
print(solve(sys.argv[1]))