From 90959212e5b0f3cfbae95ea38100e6fee4d2475f Mon Sep 17 00:00:00 2001 From: Maxim Smolskiy Date: Mon, 25 Jul 2022 19:41:12 +0300 Subject: [PATCH] perf: improve Project Euler problem 030 solution 1 (#6267) Improve solution (locally 3+ times - from 3+ seconds to ~1 second) Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> --- project_euler/problem_030/sol1.py | 32 ++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/project_euler/problem_030/sol1.py b/project_euler/problem_030/sol1.py index c9f2d7196..2c6b4e4e8 100644 --- a/project_euler/problem_030/sol1.py +++ b/project_euler/problem_030/sol1.py @@ -1,4 +1,4 @@ -""" Problem Statement (Digit Fifth Power ): https://projecteuler.net/problem=30 +""" Problem Statement (Digit Fifth Powers): https://projecteuler.net/problem=30 Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: @@ -13,26 +13,32 @@ The sum of these numbers is 1634 + 8208 + 9474 = 19316. Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. -(9^5)=59,049‬ -59049*7=4,13,343 (which is only 6 digit number ) -So, number greater than 9,99,999 are rejected -and also 59049*3=1,77,147 (which exceeds the criteria of number being 3 digit) -So, n>999 -and hence a bound between (1000,1000000) +9^5 = 59049 +59049 * 7 = 413343 (which is only 6 digit number) +So, numbers greater than 999999 are rejected +and also 59049 * 3 = 177147 (which exceeds the criteria of number being 3 digit) +So, number > 999 +and hence a number between 1000 and 1000000 """ -def digitsum(s: str) -> int: +DIGITS_FIFTH_POWER = {str(digit): digit**5 for digit in range(10)} + + +def digits_fifth_powers_sum(number: int) -> int: """ - >>> all(digitsum(str(i)) == (1 if i == 1 else 0) for i in range(100)) - True + >>> digits_fifth_powers_sum(1234) + 1300 """ - i = sum(pow(int(c), 5) for c in s) - return i if i == int(s) else 0 + return sum(DIGITS_FIFTH_POWER[digit] for digit in str(number)) def solution() -> int: - return sum(digitsum(str(i)) for i in range(1000, 1000000)) + return sum( + number + for number in range(1000, 1000000) + if number == digits_fifth_powers_sum(number) + ) if __name__ == "__main__":