Skip to content

Add second solution for the Euler project problem 13. #12764

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions project_euler/problem_013/sol2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""
Problem 13: https://projecteuler.net/problem=13

Problem Statement:
Work out the first ten digits of the sum of the following one-hundred 50-digit
numbers.
"""

import os


def solution(n: int = 10) -> str:
"""
Returns the first 'n' digits of the sum of the array elements
from the file num.txt. n should be larger than 2.

>>> solution(3)
'553'
>>> solution(6)
'553737'
"""
file_path = os.path.join(os.path.dirname(__file__), "num.txt")
numbers: list[str] = []
with open(file_path) as file_hand:
for line in file_hand:
numbers.append(line)

ans = [0] * 50
for d in range(49, -1, -1):
for num in numbers:
ans[d] += int(num[d])
if d > 0:
ans[d - 1] = ans[d] // 10
ans[d] %= 10

size_first = len(str(ans[0]))
return "".join([str(x) for x in ans[: n - size_first + 1]])


if __name__ == "__main__":
print(solution())