Tim Varley Logo
Tim Varley Systems Engineer
Problem #53 medium

Combinatoric selections

View on Project Euler

There are exactly ten ways of selecting three from five, 12345:

123, 124, 125, 134, 135, 145, 234, 235, 245, and 345

In combinatorics, we use the notation, (53)=10\binom 5 3 = 10.

In general, (nr)=n!r!(nr)!\binom n r = \dfrac{n!}{r!(n-r)!}, where rnr \le n, n!=n×(n1)×...×3×2×1n! = n \times (n-1) \times ... \times 3 \times 2 \times 1, and 0!=10! = 1.

It is not until n=23n = 23, that a value exceeds one-million: (2310)=1144066\binom {23} {10} = 1144066.

How many, not necessarily distinct, values of (nr)\binom n r for 1n1001 \le n \le 100, are greater than one-million?

Implementations

cpp
// https://projecteuler.net/problem=53
// Combinatoric selections
// There are exactly ten ways of selecting three from five, 12345: 123, 124, 125, 134, 135, 145, 234, 235, 245, and 345
// In combinatorics, we use the notation, C(5,3) = 10.
// In general, C(n,r) = n! / (r! * (n-r)!), where r ≤ n, n! = n×(n−1)×...×3×2×1, and 0! = 1.
// It is not until n = 23, that a value exceeds one-million: C(23,10) = 1144066.
// How many, not necessarily distinct, values of C(n,r) for 1 ≤ n ≤ 100, are greater than one-million?
// Answer: 4075
#include <iostream>
long long factorial(int n) {
long long res = 1;
for (int i = 2; i <= n; ++i) res *= i;
return res;
}
long long binom(int n, int r) {
if (r > n - r) r = n - r;
long long res = 1;
for (int i = 0; i < r; ++i) {
res *= (n - i);
res /= (i + 1);
}
return res;
}
int combinatoric_selections() {
int count = 0;
for (int n = 1; n <= 100; ++n) {
for (int r = 0; r <= n; ++r) {
if (binom(n, r) > 1000000) {
++count;
break;
}
}
}
return count;
}
#if ! defined UNITTEST_MODE
int main() {
std::cout << combinatoric_selections() << std::endl;
}
#endif

Solution Notes

Mathematical Background

Explores binomial coefficients and combinatorics, building on Pascal’s triangle patterns where entries grow rapidly.

Algorithm Analysis

Uses multiplicative formula for C(n,r) to compute without full factorials, with early loop breaking when exceeding 1M threshold. Time complexity optimized to O(n^2 / 2) effectively.

Key Insights

  • Threshold crossed at n=23 with C(23,10)=1,144,066
  • Central binomials grow fastest
  • 4075 combinations exceed 1M for n≤100

Educational Value

Bridges pure math with programming by demonstrating big integer avoidance techniques and efficient counting in combinatorial explosions. Perfect for understanding growth rates in probability and statistics.