Project Euler #13 Understandning (Python)

Project Euler #13 Understandning (Python)

Problem 13:

Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. So, is the question sum the 5000 digits and the answer is the first 10 digits in the result?

bignumber = list of the 5000 digits
sum(bignumber) = abcdefghijklmnopqrst...    
answer = abcdefghj

Well when I do this sum(bignumber) = 22660 (which even is not 10 digits)...

have I misread the question?

def foo():
    with open ("bignumber", "r") as myfile:
        data=myfile.read().replace('\n', '')
    data = map(long, data)
    datasum = sum(data)
    return (datasum)
4

3 Answers

You are misreading the question.

They give you 100 numbers that you need to sum, each of which is 50 digits long (aka magnitude of X*10^50). The 50 digit part is there so you cant just use traditional int/long data types (As JLLAgrange points out, this part shouldn't be a problem for python since integers have no max value).

1

Each number is 50 digits long (i.e., each line is a digit). You might try

def foo():
    with open ("bignumber", "r") as myfile:
        data=myfile.read()
    data = map(int, data)
    datasum = sum(data)
    return datasum

I think you understood the question correctly, but applied wrongly in Python.

You are doing:

with open ("bignumber", "r") as myfile:
    data=myfile.read().replace('\n', '')
    #Now `data` is a big huge string of digits
data = map(long, data)
#Now data is an array of 5000 elements of each digit.
#And then you are trying sum this array of digits.

What you need:

with open(..) as fileObj:
    data = [long(line.strip()) for line in fileObj]

Look at this example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.