Project Euler Problem 13 Solution

Project Euler Problem 13 Solution

Large sum

by {BetaProjects} | Project Euler & HackerRank

Project Euler Problem 13 Statement

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

37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
… {data continues}

Solution

Summing a set of 50–digit numbers uses Python’s intrinsic arbitrary–precision integers and arithmetic.

The numbers to add are saved to a file named pe13.txt. This keeps the data and the program separate and the process easy to comprehend.

The file is read as strings and converted to a list of integers using the map function with open as the iterator and int as the application function. After the end of the file is reached the list is fed to the sum function which adds the integers together.

total = sum(map(int, open('pe13.txt')))

Finally, the integer sum, total, is converted to a string and truncated to the top 10 digits for a solution.

str(total)[:10]

HackerRank version

HackerRank increases the quantity of 50–digit numbers from 100 to 1,000. No changes are required.

Python Source Code

total = sum(map(int, open('pe13.txt')))
print ("Top 10 digits of sum =", str(total)[:10])	

Last Word

The data file, pe13.txt, is available on repl.it page by clicking the files repl.it external files icon in the top left corner.