Bit Manipulation · Pattern 6 of 6

Bits meet number theory: gcd and powers of two

Some puzzles hide a number theory fact about powers of two. Find what never changes under the allowed moves (here, the odd part of the gcd), then the bit trick g & (g - 1) == 0 answers the question.

1 variation · 1 problem

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Moves that double, halve, add or subtract coordinates
  • Ask whether a target can be reached at all
  • The answer depends only on the gcd or on factors of 2

The template

Math / Number Theory
int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
}

boolean isReachable(int targetX, int targetY) {
    int g = gcd(targetX, targetY);
    return (g & (g - 1)) == 0;              // the gcd must be a power of two
}

The variations

  1. 1Find the invariant, then test a power of two

    Subtracting one coordinate from the other keeps the gcd, and doubling can only multiply it by 2. Starting from (1, 1), every reachable point has a gcd that is a power of two, and working backwards shows every such point is reachable.

Mistakes to avoid

  • Searching the moves with BFS: the coordinates go up to 10^9, so the search never ends.
  • Checking only whether the gcd is 1: doubling keeps powers of two, so a gcd of 2, 4 or 8 is still reachable.
Back to Bit Manipulation →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.