From 1dc0388650df2e49bc55023eb3453d283c7515a2 Mon Sep 17 00:00:00 2001 From: Nayuki Minase Date: Mon, 27 Jul 2015 19:30:06 +0000 Subject: [PATCH] P34, P70, P92: Optimized Python solutions. --- python/p034.py | 13 +++++++------ python/p070.py | 2 +- python/p092.py | 7 ++++--- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/python/p034.py b/python/p034.py index 6a97c57..ddee314 100644 --- a/python/p034.py +++ b/python/p034.py @@ -17,14 +17,15 @@ def compute(): return str(ans) -FACTORIAL = list(map(eulerlib.factorial, range(10))) - def factorial_digit_sum(n): result = 0 - while n > 0: - result += FACTORIAL[n % 10] - n //= 10 - return result + while n >= 10000: + result += FACTORIAL_DIGITS_SUM_WITH_LEADING_ZEROS[n % 10000] + n //= 10000 + return result + FACTORIAL_DIGITS_SUM_WITHOUT_LEADING_ZEROS[n] + +FACTORIAL_DIGITS_SUM_WITHOUT_LEADING_ZEROS = [sum(eulerlib.factorial(int(c)) for c in str(i)) for i in range(10000)] +FACTORIAL_DIGITS_SUM_WITH_LEADING_ZEROS = [sum(eulerlib.factorial(int(c)) for c in str(i).zfill(4)) for i in range(10000)] if __name__ == "__main__": diff --git a/python/p070.py b/python/p070.py index a4354d2..eaa90f9 100644 --- a/python/p070.py +++ b/python/p070.py @@ -17,7 +17,7 @@ def compute(): minnumer = 1 mindenom = 0 for (i, tot) in enumerate(totients[2 : ], 2): - if sorted(str(i)) == sorted(str(tot)) and i * mindenom < minnumer * tot: + if i * mindenom < minnumer * tot and sorted(str(i)) == sorted(str(tot)): minnumer = i mindenom = totients[i] return str(minnumer) diff --git a/python/p092.py b/python/p092.py index fe442cc..765e961 100644 --- a/python/p092.py +++ b/python/p092.py @@ -20,11 +20,12 @@ def compute(): def square_digit_sum(n): result = 0 while n > 0: - x = n % 10 - result += x * x - n //= 10 + result += SQUARE_DIGITS_SUM[n % 1000] + n //= 1000 return result +SQUARE_DIGITS_SUM = [sum(int(c)**2 for c in str(i)) for i in range(1000)] + if __name__ == "__main__": print(compute()) -- 2.22.0