6

Problem 13: http://projecteuler.net/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)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Isbister
  • 906
  • 1
  • 12
  • 30
  • The question is to sum the 100 numbers, not to sum their digits. – Russell Zahniser Nov 21 '13 at 15:28
  • 2
    It's the difference between 12+34 and 1+2+3+4. – Sven Marnach Nov 21 '13 at 15:29
  • 1
    Note that the question is a bit easier in python, since integers have no maximum: http://stackoverflow.com/questions/4581842/python-integer-ranges, so you do not have to deal with overflow. – colcarroll Nov 21 '13 at 15:31
  • Lets say someone wanted to do this in another language like C#. How could they overcome the limitations of the ulong being only 20 digits max in length? –  Apr 26 '22 at 17:53

3 Answers3

5

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).

Colin D
  • 5,641
  • 1
  • 23
  • 35
0

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
colcarroll
  • 3,632
  • 17
  • 25
0

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

UltraInstinct
  • 43,308
  • 12
  • 81
  • 104