Tim Varley Logo
Tim Varley Principal AI Engineer and Tech Leader
Problem #99 easy

Largest exponential

Comparing two numbers written in index form like 2112^{11} and 373^7 is not difficult, as any calculator would confirm that 211=2048<37=21872^{11} = 2048 \lt 3^7 = 2187.

However, confirming that 632382518061>519432525806632382^{518061} \gt 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.

View on Project Euler

Implementations

cpp
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
long long largest_exponential() {
std::ifstream file("src/p099_base_exp.txt");
if (!file) return 0;
std::string line;
int line_num = 0;
int max_line = 0;
double max_val = 0;
while (std::getline(file, line)) {
line_num++;
size_t comma = line.find(',');
int base = std::stoi(line.substr(0, comma));
int exp = std::stoi(line.substr(comma + 1));
double val = exp * std::log(base);
if (val > max_val) {
max_val = val;
max_line = line_num;
}
}
return max_line;
}

Solution Notes

Mathematical Background

Comparing large exponentials b^e without computing the actual values. Since log is monotonic, compare e * log(b) instead.

Algorithm Analysis

Read each base-exponent pair from file, compute exp * log(base), track maximum value and its line number.

Performance

Extremely fast (~1ms) due to simple file reading and logarithmic computations.

Key Insights

  • Logarithmic comparison avoids overflow and precision issues with huge numbers
  • Direct file parsing with string splitting

Educational Value

Demonstrates logarithmic transformations for comparing large numbers and basic file I/O in multiple languages.

Problem #99 is taken from Project Euler and licensed under CC BY-NC-SA 4.0.