Skip to content

Commit c5b2dee

Browse files
committed
Add second solution for the Euler project problem 13.
1 parent 0c8cf8e commit c5b2dee

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

project_euler/problem_013/sol2.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""
2+
Problem 13: https://projecteuler.net/problem=13
3+
4+
Problem Statement:
5+
Work out the first ten digits of the sum of the following one-hundred 50-digit
6+
numbers.
7+
"""
8+
9+
import os
10+
11+
12+
def solution(n: int = 10) -> str:
13+
"""
14+
Returns the first 'n' digits of the sum of the array elements
15+
from the file num.txt. n should be larger than 2.
16+
17+
>>> solution(3)
18+
'553'
19+
>>> solution(6)
20+
'553737'
21+
"""
22+
file_path = os.path.join(os.path.dirname(__file__), "num.txt")
23+
numbers: list[str] = []
24+
with open(file_path) as file_hand:
25+
for line in file_hand:
26+
numbers.append(line)
27+
28+
ans = [0] * 50
29+
for d in range(49, -1, -1):
30+
for num in numbers:
31+
ans[d] += int(num[d])
32+
if d > 0:
33+
ans[d - 1] = ans[d] // 10
34+
ans[d] %= 10
35+
36+
size_first = len(str(ans[0]))
37+
return "".join([str(x) for x in ans[: n - size_first + 1]])
38+
39+
40+
if __name__ == "__main__":
41+
print(solution())

0 commit comments

Comments
 (0)