A diagonal through a box

The question

A solid block is built from unit cubes, 2 along one edge, 3 along the next and 6 along the last. A straight rod is pushed from one corner right through to the opposite corner.

How many of the little cubes does it pass through?

Count the walls, then the ones crossed together

naive:11
11−6=5
5+1=6
  1. A rod goes corner to corner through an 2 × 3 × 6 block of unit cubes. It enters a new cube every time it crosses a wall — so a first guess is 2 + 3 + 6 = 11.
  2. But where two walls meet on one line the rod crosses both at once, and that split was counted twice. It happens gcd(2,3) = 1, gcd(3,6) = 3 and gcd(6,2) = 2 times — 6 in all — so take them off: 11 − 6 = 5.
  3. Where all three walls meet at a corner point it was subtracted once too often, so add gcd(2,3,6) = 1 back: 5 + 1 = 6.

How it works.

  1. 01

    A rod goes corner to corner through an 2 × 3 × 6 block of unit cubes. It enters a new cube every time it crosses a wall — so a first guess is 2 + 3 + 6 = 11.

  2. 02

    But where two walls meet on one line the rod crosses both at once, and that split was counted twice. It happens gcd(2,3) = 1, gcd(3,6) = 3 and gcd(6,2) = 2 times — 6 in all — so take them off: 11 − 6 = 5.

  3. 03

    Where all three walls meet at a corner point it was subtracted once too often, so add gcd(2,3,6) = 1 back: 5 + 1 = 6.