Use sieve method instead of algebraic method

This commit is contained in:
Peter J. Holzer 2020-12-14 22:02:32 +01:00 committed by Peter J. Holzer
parent 272523b8b2
commit 259f974f32
1 changed files with 26 additions and 44 deletions

View File

@ -1,50 +1,32 @@
#!/usr/bin/python3
import time
def ext_euclid(a, b):
"""
returns solutions x and y for equation ax + by = gcd(a, b)
"""
def shuttle_generator():
with open("input") as fh:
now = int(fh.readline())
for i, x in enumerate(fh.readline().split(",")):
if x != "x":
x = int(x)
yield i, x
(old_r, r) = (a, b)
(old_s, s) = (1, 0)
(old_t, t) = (0, 1)
shuttle = shuttle_generator()
while r:
quotient = old_r // r
(old_r, r) = (r, old_r - quotient * r)
(old_s, s) = (s, old_s - quotient * s)
(old_t, t) = (t, old_t - quotient * t)
return old_s, old_t, old_r
def check(t, tests):
for i, n in tests:
if (t + i) % n != 0:
return False
return True
n = []
a = []
with open("input") as fh:
now = int(fh.readline())
for i, x in enumerate(fh.readline().split(",")):
if x != "x":
x = int(x)
n.append(x)
a.append((x - i) % x)
t = 0
step = 1
n = 1
tests = []
while True:
if check(t, tests):
print(t, "matches", tests)
time.sleep(2)
step *= n
i, n = next(shuttle)
tests.append((i, n))
t += step
print(n)
print(a)
n1 = n.pop()
n2 = n.pop()
a1 = a.pop()
a2 = a.pop()
m1, m2, _ = ext_euclid(n1, n2)
assert _ == 1
x = a1 * m2 * n2 + a2 * m1 * n1
print(x)
while n:
n1 = n1 * n2
a1 = x
n2 = n.pop()
a2 = a.pop()
m1, m2, _ = ext_euclid(n1, n2)
assert _ == 1
x = a1 * m2 * n2 + a2 * m1 * n1
print(x)