Skip to content

Commit 6befcf8

Browse files
committed
Add third solution for the Euler project problem 16.
1 parent a2fa32c commit 6befcf8

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

project_euler/problem_016/sol3.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"""
2+
Problem 16: https://projecteuler.net/problem=16
3+
4+
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
5+
6+
What is the sum of the digits of the number 2^1000?
7+
"""
8+
9+
from numpy import log10, zeros
10+
11+
12+
def solution(power: int = 1000) -> int:
13+
"""
14+
Calculates the sum of digits by explicit construction of digits array
15+
without the help of Python's large integer property.
16+
17+
>>> solution(50)
18+
76
19+
>>> solution(20)
20+
31
21+
>>> solution(15)
22+
26
23+
>>> solution(3)
24+
8
25+
"""
26+
27+
digits = zeros(int(power * log10(2)) + 1)
28+
digits[0] = 1
29+
dig_count = 1
30+
for _ in range(power):
31+
carry = 0
32+
for d in range(dig_count):
33+
digits[d] = digits[d] * 2 + carry
34+
carry = digits[d] // 10
35+
digits[d] %= 10
36+
if carry > 0:
37+
digits[dig_count] = carry
38+
dig_count += 1
39+
40+
return int(sum(digits))
41+
42+
43+
if __name__ == "__main__":
44+
print(solution())

0 commit comments

Comments
 (0)