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

Prime power triples

The smallest number expressible as the sum of a prime square, prime cube, and prime fourth power is 28. In fact, there are exactly four numbers below fifty that can be expressed in such a way:

  • 28 = 2² + 2³ + 2⁴

  • 33 = 3² + 2³ + 2⁴

  • 49 = 5² + 2³ + 2⁴

  • 47 = 2² + 3³ + 2⁴

How many numbers below fifty million can be expressed as the sum of a prime square, prime cube, and prime fourth power?"

View on Project Euler

Implementations

cpp
#include <iostream>
#include <vector>
#include <set>
const long long LIMIT = 50000000;
std::vector<int> primes;
void generate_primes(int max_n) {
std::vector<bool> is_prime(max_n + 1, true);
is_prime[0] = is_prime[1] = false;
for (long long i = 2; i <= max_n; ++i) {
if (is_prime[i]) {
primes.push_back(i);
for (long long j = i * i; j <= max_n; j += i) {
is_prime[j] = false;
}
}
}
}
long long prime_power_triples() {
int max_prime = 0;
while ((long long)max_prime * max_prime < LIMIT) max_prime++;
max_prime--;
generate_primes(max_prime);
std::set<long long> numbers;
for (int p4 : primes) {
long long fourth = (long long)p4 * p4 * p4 * p4;
if (fourth >= LIMIT) break;
for (int p3 : primes) {
long long cube = (long long)p3 * p3 * p3;
if (fourth + cube >= LIMIT) break;
for (int p2 : primes) {
long long square = (long long)p2 * p2;
long long sum = fourth + cube + square;
if (sum >= LIMIT) break;
numbers.insert(sum);
}
}
}
return numbers.size();
}

Solution Notes

Mathematical Background

This problem asks to count distinct numbers below 50 million that can be written as p² + q³ + r⁴ where p, q, r are prime numbers. It involves generating primes and computing all possible combinations of prime powers that sum to less than the limit.

Algorithm Analysis

Generate all primes up to √50M using sieve. Then use three nested loops over primes for squares, cubes, and fourth powers, computing sums and storing unique values in a set. Early termination when sums exceed the limit.

Time complexity: O(P³) where P is number of primes (~7000), but with early breaks it’s much faster. Space complexity: O(P) for primes list, O(N) for the set of sums where N is the count of unique numbers.

Performance

Very fast across implementations (<200ms), as the nested loops are optimized with early exits and the number of primes is small.

Key Insights

The key is to generate primes only once and use sets to handle duplicates automatically. The order of loops (fourth powers outermost) helps with early termination.

Educational Value

Demonstrates efficient prime generation with sieve, combinatorial enumeration with early pruning, and the use of sets for uniqueness in counting problems.

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