Project Euler Solution 99: Largest exponential

In Problem 99: Largest exponential we are given a bunch of base exponent pairs and have to order these exponential numbers.

Comparing two numbers written in index form like $2^{11}$ and $3^7$ is not difficult, as any calculator would confirm that $2^{11} = 2048 < 3^7 = 2187$.

However, confirming that $632382^{518061} > 519432^{525806}$ would be much more difficult, as both numbers contain over three million digits.

Using base_exp.txt, a 22K text file containing one thousand lines with a base/exponent pair on each line, determine which line number has the greatest numerical value.

NOTE: The first two lines in the file represent the numbers in the example given above.

We first write a function that gets the numbers parsed:

def get_pairs() -> list[tuple[int, int]]:
    with open("data/p099_base_exp.txt") as f:
        return [tuple(map(int, line.split(","))) for line in f]

Then we could actually compute $a^b$ and then sort these. But we can be a bit more clever here. We can apply the logarithm and convert $a^b$ into $b \log a$. The logarithm is a strictly monotonic function, therefore it doesn't alter the order of the numbers. This trick then lets us compute the logarithm of all these numbers and sort them. In the end we take the largest number.

def solution_logarithm() -> int:
    pairs = get_pairs()
    numbers = [exponent * math.log(base) for base, exponent in pairs]
    argmax = sorted(enumerate(numbers, 1), key=lambda t: t[1])[-1][0]
    return argmax

That runs in 0.957 ms and seems to be the obvious and fast solution.