Project Euler Problem 99 Solution

Project Euler Problem 99 Solution

Largest Exponential

by {BetaProjects} | Project Euler & HackerRank

Project Euler Problem 99 Statement

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 \lt 3^7 = 2187$.

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

Using base_exp.txt (right click and 'Save Link/Target As...'), 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.

Solution

This problem is solved by using logarithms to compare exponential numbers without actually computing them. This allows comparison of massive numbers that would be impossible to compute directly due to overflow or computational limitations.

We first read $N$ base–exponent pairs from input then apply the logarithm property: $\log{b^e} = e \cdot \log{b}$ to each pair. Each tuple now contains $(e \cdot \log{b}$, original_base, original_exponent). This lets us compare huge powers without calculating them directly.

All that's left to do is sort the tuples (they'll be sorted by $e \cdot \log{b}$ value) and print the Kth ordinal position base–exponent pair from sorted list.

HackerRank version

HackerRank Project Euler 99 given a list of base/exponent pairs print the largest exponet. 1 ≤ B,E ≤ 109.

Python Source Code

import math
v = [tuple(map(int, input().split())) for _ in range(int(input()))]
v = [(e * math.log(b), b, e) for b, e in v]

K = int(input())
_, b, e = sorted(v)[K-1]
print(b, e)	

Last Word