Learn / Maths for DSA

Inclusion-exclusion

To count items with at least one of several properties, add the counts for each property, subtract the counts for each pair, add back each triple, and so on. Typical uses: numbers up to n divisible by any of a few primes, or arrangements avoiding several bad events. The sheets this guide follows have no problems for this pattern.

How to recognise it

  • Count elements with at least one of a few properties.
  • Counting the complement (none of the properties) is easier.
  • Up to about 20 properties, so all subsets can be listed.

Signs by subset size

total = 0
for every non-empty subset S of the properties:
    count = items having every property in S
    total += count if |S| is odd else -count

Derangements are a classic example: n! minus the arrangements with some fixed point, worked out by subset size.

Common mistakes

  • Wrong signs for even subsets.
  • For divisibility, dividing by the product instead of the least common multiple.

Problems

No problems listed for this pattern yet.

Check yourself

Numbers from 1 to 30 divisible by 2 or 3?

Why subtract pairs?

How many terms are there for k properties?