Skip to content

Commit 9095921

Browse files
MaximSmolskiygithub-actions
and
github-actions
authored
perf: improve Project Euler problem 030 solution 1 (TheAlgorithms#6267)
Improve solution (locally 3+ times - from 3+ seconds to ~1 second) Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
1 parent 7d9ebee commit 9095921

File tree

1 file changed

+19
-13
lines changed

1 file changed

+19
-13
lines changed

project_euler/problem_030/sol1.py

+19-13
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
""" Problem Statement (Digit Fifth Power ): https://projecteuler.net/problem=30
1+
""" Problem Statement (Digit Fifth Powers): https://projecteuler.net/problem=30
22
33
Surprisingly there are only three numbers that can be written as the sum of fourth
44
powers of their digits:
@@ -13,26 +13,32 @@
1313
Find the sum of all the numbers that can be written as the sum of fifth powers of their
1414
digits.
1515
16-
(9^5)=59,049‬
17-
59049*7=4,13,343 (which is only 6 digit number )
18-
So, number greater than 9,99,999 are rejected
19-
and also 59049*3=1,77,147 (which exceeds the criteria of number being 3 digit)
20-
So, n>999
21-
and hence a bound between (1000,1000000)
16+
9^5 = 59049
17+
59049 * 7 = 413343 (which is only 6 digit number)
18+
So, numbers greater than 999999 are rejected
19+
and also 59049 * 3 = 177147 (which exceeds the criteria of number being 3 digit)
20+
So, number > 999
21+
and hence a number between 1000 and 1000000
2222
"""
2323

2424

25-
def digitsum(s: str) -> int:
25+
DIGITS_FIFTH_POWER = {str(digit): digit**5 for digit in range(10)}
26+
27+
28+
def digits_fifth_powers_sum(number: int) -> int:
2629
"""
27-
>>> all(digitsum(str(i)) == (1 if i == 1 else 0) for i in range(100))
28-
True
30+
>>> digits_fifth_powers_sum(1234)
31+
1300
2932
"""
30-
i = sum(pow(int(c), 5) for c in s)
31-
return i if i == int(s) else 0
33+
return sum(DIGITS_FIFTH_POWER[digit] for digit in str(number))
3234

3335

3436
def solution() -> int:
35-
return sum(digitsum(str(i)) for i in range(1000, 1000000))
37+
return sum(
38+
number
39+
for number in range(1000, 1000000)
40+
if number == digits_fifth_powers_sum(number)
41+
)
3642

3743

3844
if __name__ == "__main__":

0 commit comments

Comments
 (0)