Python Implementation of Problem 99

View source code here on GitHub!

Includes

Problem Solution

Project Euler Problem 99

Comparing two numbers written in index form like 211 and 37 is not difficult, as any calculator would confirm that 211 = 2048 < 37 = 2187.

However, confirming that 632382518061 > 519432525806 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.

python.src.p0099.cmp_two_exp(pair1: Tuple[int, float], pair2: Tuple[int, float]) int
python.src.p0099.main() int
 1"""
 2Project Euler Problem 99
 3
 4Comparing two numbers written in index form like 211 and 37 is not difficult, as any calculator would confirm that
 5211 = 2048 < 37 = 2187.
 6
 7However, confirming that 632382518061 > 519432525806 would be much more difficult, as both numbers contain over three
 8million digits.
 9
10Using base_exp.txt (right click and 'Save Link/Target As...'), a 22K text file containing one thousand lines with a
11base/exponent pair on each line, determine which line number has the greatest numerical value.
12
13NOTE: The first two lines in the file represent the numbers in the example given above.
14"""
15from functools import cmp_to_key
16from math import log
17from typing import List, Tuple
18
19from .lib.utils import get_data_file
20
21
22def cmp_two_exp(pair1: Tuple[int, float], pair2: Tuple[int, float]) -> int:
23    base1, exp1 = pair1
24    base2, exp2 = pair2
25    exp1 *= log(base1)
26    exp2 *= log(base2)
27    if exp1 == exp2:
28        return 0
29    elif exp1 > exp2:
30        return 1
31    return -1
32
33
34def main() -> int:
35    candidates: List[Tuple[int, int]] = []
36    for line in get_data_file('p0099_base_exp.txt', 'r').splitlines():
37        x, y = line.rstrip('\n').split(',')
38        candidates.append((int(x), int(y)))
39    return max(enumerate(candidates, 1), key=lambda x: cmp_to_key(cmp_two_exp)(x[1]))[0]

Tags: power, large-numbers, file-io