Counting Summations
It is possible to write five as a sum in exactly six different ways:
4 + 1
3 + 2
3 + 1 + 1
2 + 2 + 1
2 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1
How many different ways can one hundred be written as a sum of at least two positive integers?
Implementations
#include <iostream>#include <vector>
int counting_summations() { const int N = 100; std::vector<long long> p(N + 1, 0); p[0] = 1; for (int i = 1; i <= N; ++i) { for (int j = i; j <= N; ++j) { p[j] += p[j - i]; } } return p[N] - 1;}
#if ! defined UNITTEST_MODEint main(int argc, char const *argv[]) { std::cout << counting_summations() << std::endl;}#endifSolution Notes
Mathematical Background
The problem asks for the number of ways to write 100 as a sum of positive integers, where order doesn’t matter, minus the trivial case of 100 itself.
This relates to the partition function p(n), which counts the number of distinct partitions of n. The partition function p(n) gives the number of ways to write n as a sum of positive integers where order doesn’t matter.
The solution uses dynamic programming to compute p(n), then subtracts 1 to exclude the partition consisting of n itself.
Algorithm Analysis
The implementations use a dynamic programming approach where dp[j] represents the number of ways to sum to j.
Initialize dp[0] = 1 (one way to sum to 0: nothing).
For each possible summand i from 1 to n, update dp[j] for j from i to n by adding dp[j - i].
This counts ordered partitions, but since we’re dealing with sums where order doesn’t matter for the problem (as the examples show unordered), but the DP counts ordered, but for the partition function, it’s the same.
The DP actually computes the number of unrestricted partitions.
Yes, the code computes p(n), the partition function.
Subtract 1 for the single number case.
Performance Analysis
- Time Complexity: O(n²) due to nested loops over n
- Space Complexity: O(n) for the DP array
- Execution Time: Fast for n=100, milliseconds on modern hardware
- Scalability: Quadratic, suitable for small n like 100
Key Insights
- The partition function grows very rapidly
- Dynamic programming provides an efficient way to compute partitions
- Subtracting 1 excludes the trivial partition
Educational Value
This problem introduces:
- The concept of integer partitions
- Dynamic programming for counting problems
- The difference between ordered and unordered partitions
Problem #76 is taken from Project Euler and licensed under CC BY-NC-SA 4.0.