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