Back to Project Euler

Previous Problem Next Problem

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, (53)=10.

In general, (nr)=n!r!(nr)!, where rn, n!=n×(n1)×...×3×2×1, and 0!=1.

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

How many, not necessarily distinct, values of (nr) for 1n100, are greater than one-million?

Solution

The binomial coefficients with fixed n form the (n+1)-st row of Pascal's triangle. It can be seen that (nr)=(nnr), and that the coefficients in a row strictly increase until the midpoint. Therefore, if kn is the minimum number such that (nkn) is greater than one million, then all of (nkn+1),(nkn+2),,(nnkn) are greater than one million, for a total of n2kn+1 values. The problem then reduces to finding kn for all n23.

Pascal's rule states that (n1k)+(n1k1)=(nk); and so if (n1k) is greater than one million, then so is (nk). Thus our starting point for kn is kn1, and we decrease kn until doing so would put the binomial coefficient below one million.

To avoid having to compute the binomial coefficient from scratch every time, my program uses the helpful identities (n+1k)=n+1nk+1(nk) and (nk1)=knk+1(nk).

Python Code

def p53():
	binom = 1144066
	k = 10
	res = 0
	for n in range(23, 101):
		while binom * k // (n-k+1) > 10**6:
			binom = binom * k // (n-k+1)
			k -= 1
		res += n - 2*k + 1
		binom = binom * (n+1) // (n-k+1)
	return res

Previous Problem Next Problem

Back to Project Euler