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>
This commit is contained in:
Maxim Smolskiy 2022-07-25 19:41:12 +03:00 committed by GitHub
parent 7d9ebee75f
commit 90959212e5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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 Surprisingly there are only three numbers that can be written as the sum of fourth
powers of their digits: 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 Find the sum of all the numbers that can be written as the sum of fifth powers of their
digits. digits.
(9^5)=59,049 9^5 = 59049
59049*7=4,13,343 (which is only 6 digit number ) 59049 * 7 = 413343 (which is only 6 digit number)
So, number greater than 9,99,999 are rejected So, numbers greater than 999999 are rejected
and also 59049*3=1,77,147 (which exceeds the criteria of number being 3 digit) and also 59049 * 3 = 177147 (which exceeds the criteria of number being 3 digit)
So, n>999 So, number > 999
and hence a bound between (1000,1000000) 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)) >>> digits_fifth_powers_sum(1234)
True 1300
""" """
i = sum(pow(int(c), 5) for c in s) return sum(DIGITS_FIFTH_POWER[digit] for digit in str(number))
return i if i == int(s) else 0
def solution() -> int: 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__": if __name__ == "__main__":