Prime Summations
It is possible to write ten as the sum of primes in exactly five different ways:
7 + 3
5 + 5
5 + 3 + 2
3 + 3 + 2 + 2
2 + 2 + 2 + 2 + 2
What is the first value which can be written as the sum of primes in over five thousand different ways?
Implementations
#include <iostream>#include <vector>
int prime_summations() { const int N = 1000; std::vector<bool> is_prime(N + 1, true); is_prime[0] = is_prime[1] = false; for (long long i = 2; i <= N; ++i) { if (is_prime[i]) { for (long long j = i * i; j <= N; j += i) { is_prime[j] = false; } } } std::vector<int> primes; for (int i = 2; i <= N; ++i) { if (is_prime[i]) primes.push_back(i); } std::vector<long long> ways(N + 1, 0); ways[0] = 1; for (int p : primes) { for (int j = p; j <= N; ++j) { ways[j] += ways[j - p]; } } for (int n = 2; n <= N; ++n) { if (ways[n] > 5000) return n; } return -1;}
#if ! defined UNITTEST_MODEint main(int argc, char const *argv[]) { std::cout << prime_summations() << std::endl;}#endifSolution Notes
Mathematical Background
The problem asks for the smallest number that can be expressed as the sum of primes in more than 5000 different ordered ways.
This involves counting the number of ordered prime partitions of n, using dynamic programming similar to the coin change problem but with primes as denominations.
Algorithm Analysis
Generate all primes up to a limit using the Sieve of Eratosthenes.
Use DP where ways[j] is the number of ways to sum to j using the primes.
Initialize ways[0] = 1.
For each prime p, for j from p to limit, ways[j] += ways[j - p].
Find the smallest n where ways[n] > 5000.
Performance Analysis
- Time Complexity: O(n²) due to nested loops
- Space Complexity: O(n) for prime and ways arrays
- Execution Time: Very fast for n=1000
- Scalability: Quadratic, efficient for this scale
Key Insights
- Uses ordered partitions (compositions) of primes
- The answer is 71, which has 5001 ordered prime sums
Educational Value
This problem teaches:
- Prime generation with sieves
- Dynamic programming for counting compositions
- The difference between ordered and unordered partitions
Problem #77 is taken from Project Euler and licensed under CC BY-NC-SA 4.0.