Project Euler Problem 99 Solution

Project Euler Problem 99 Solution

Largest Exponential

by {BetaProjects} | Project Euler & HackerRank
Difficulty: Medium

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

HackerRank Project Euler Problem 99 overview:

Given a list of $N$, $(1\le N\le 10^5)$ base $(B)$/exponent$(E)$ pairs find the $Kth$ smallest. Where $1\le B,E\le 10^9$ and $1\le K\le N$.

Solution Detail

This problem is solved by using logarithms to compare exponential numbers without actually computing them. Since the logarithm function is monotonically increasing, comparing these logarithmic values is equivalent to comparing the original numbers.

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 in ascending order (they'll be sorted by $e \cdot \log{b}$ value) and print the Kth ordinal position (K-1) base–exponent pair from sorted list.

HackerRank version

HackerRank Project Euler 99: Given a list of $N$, (1 ≤ N ≤ 10^5) base (B)/exponent(E) pairs find the $Kth$ smallest. Where 1 ≤ B,E ≤ 10^9 and 1 ≤ K ≤ N.

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)