Coin Partitions
Let p(n) represent the number of different ways in which n coins can be separated into piles. For example, five coins can be separated into piles in exactly seven different ways, so p(5)=7.
OOOOO
OOOO | O
OOO | OO
OOO | O | O
OO | OO | O
OO | O | O | O
O | O | O | O | O
Find the least value of n for which p(n) is divisible by one million.
Implementations
#include <iostream>#include <vector>
int coin_partitions() { const int MOD = 1000000; const int MAXN = 100000; std::vector<long long> p(MAXN + 1, 0); p[0] = 1; for (int n = 1; n <= MAXN; ++n) { int i = 1; while (true) { int pent1 = i * (3 * i - 1) / 2; if (pent1 > n) break; long long sign = (i % 2 == 1) ? 1LL : -1LL; p[n] = (p[n] + sign * p[n - pent1]) % MOD; int pent2 = i * (3 * i + 1) / 2; if (pent2 > n) break; p[n] = (p[n] + sign * p[n - pent2]) % MOD; ++i; } p[n] = (p[n] % MOD + MOD) % MOD; if (p[n] == 0 && n > 0) return n; } return -1;}
#if ! defined UNITTEST_MODEint main(int argc, char const *argv[]) { std::cout << coin_partitions() << std::endl;}#endifSolution Notes
Mathematical Background
The problem asks for the smallest n such that the partition function p(n) is divisible by 1,000,000.
The partition function p(n) counts the number of ways to write n as a sum of positive integers, ignoring order.
The solution uses the pentagonal number theorem, which gives a recurrence for p(n) using generalized pentagonal numbers.
Algorithm Analysis
The recurrence is p(n) = sum over k of (-1)^{k-1} * p(n - pent(k)) where pent(k) = k(3k-1)/2.
We compute this modulo 1,000,000 to find when p(n) ≡ 0 mod 10^6.
Performance Analysis
- Time Complexity: O(n√n) due to the inner loop over pentagonal numbers
- Space Complexity: O(n) for the partition array
- Execution Time: Moderate, around 1-2 seconds for n~50k
- Scalability: Efficient for this problem size
Key Insights
- Uses modular arithmetic to avoid large numbers
- The answer is 55374, a large number requiring efficient computation
Educational Value
This problem teaches:
- The partition function and its properties
- Pentagonal number theorem
- Modular arithmetic in combinatorial problems
Problem #78 is taken from Project Euler and licensed under CC BY-NC-SA 4.0.