From 8b1a4fa6ef7f4091544f5d67a02b8a16a22af3fe Mon Sep 17 00:00:00 2001 From: Felix Martin Date: Thu, 1 Aug 2019 09:38:51 -0400 Subject: [PATCH] Solve 71 in Python. --- python/e071.py | 30 ++++++++++++++++++++++++++++-- python/lib_misc.py | 1 + 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/python/e071.py b/python/e071.py index 49a122e..cbfc096 100644 --- a/python/e071.py +++ b/python/e071.py @@ -1,8 +1,34 @@ +from lib_misc import gcd + + +def smallest_fraction_with_new_denominator(n, d, d_new): + return (int(d_new / d * n), d_new) + def euler_071(): - return 0 + """ + The idea is to find the the closest fraction to (n, d) for every potential + new denominator d_new. We do that by extrapolating (n, d) to d_new and + rounding n_new down. This is what smallest_fraction_with_new_denominator + does. + + We can then check if the greatest common divisor for n_new and d_new is + one. I though it might be necessary to search for the next smallest n_new + if gcd(n_new, d_new) > 1, but it turned out that this is not actually + necessary. + """ + n = 3 + d = 7 + n_min, d_min = 0, 1 + for d_new in range(950000, 1000000): + n_new, d_new = smallest_fraction_with_new_denominator(n, d, d_new) + if d_new == d: + pass + elif gcd(n_new, d_new) == 1 and n_new / d_new > n_min / d_min: + n_min, d_min = n_new, d_new + return n_min if __name__ == "__main__": print("e071.py: " + str(euler_071())) - assert(euler_071() == 0) + assert(euler_071() == 428570) diff --git a/python/lib_misc.py b/python/lib_misc.py index 7552b4f..1d13e0e 100644 --- a/python/lib_misc.py +++ b/python/lib_misc.py @@ -195,6 +195,7 @@ def permutations(iterable): yield elem + ps +@lru_cache(maxsize=1000000) def gcd(a, b): while a % b != 0: a, b = b, a % b