Project Euler Solution 13: Large sum

This is part of the Project Euler series, this is about Problem 13: Large sum. One has to sum up hundred integers with 50 digits.

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

In Python this is really trivial because the integers just become as big as they need to be. Therefore one can just parse and sum them all and get the desired result.

data = """
37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
[…]
53503534226472524250874054075591789781264330331690
"""


def get_numbers() -> list[int]:
    return [int(line) for line in data.strip().split()]


def solution_big_ints() -> int:
    full_sum = sum(get_numbers())
    return int(str(full_sum)[:10])

This computes the answer 5,537,376,230 in 37 µs.

But say that we don't have the big integers. What could we do? Since we are only interested in the leading digits, we could use floats. They have around 17 digits of precision, so that is enough here.

def solution_float() -> int:
    floats = [float(number) for number in get_numbers()]
    return int(str(int(sum(floats)))[:10])

This gets the solution in 43 µs, the conversion to float apparently costs a bit more time.

A similar way would be to truncate the integers to 11 digits and then add those:

def solution_truncate() -> int:
    truncated = [number // 10**39 for number in get_numbers()]
    return int(str(sum(truncated))[:10])

Interestingly that takes 68 µs, likely because that big integer division is a lot of work.

There are many ways to do this, but Python makes the easiest way the fastet in both programming and execution time.