Largest exponential
Comparing two numbers written in index form like and is not difficult, as any calculator would confirm that .
However, confirming that 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.
Implementations
#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.