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.
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
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
} from math import gcd
def is_reachable(target_x, target_y):
g = gcd(target_x, target_y)
return (g & (g - 1)) == 0 # the gcd must be a power of two bool isReachable(int targetX, int targetY) {
int g = __gcd(targetX, targetY); // or std::gcd from <numeric> (C++17)
return (g & (g - 1)) == 0; // the gcd must be a power of two
} function gcd(a, b) {
return b === 0 ? a : gcd(b, a % b);
}
function isReachable(targetX, targetY) {
const g = gcd(targetX, targetY);
return (g & (g - 1)) === 0; // the gcd must be a power of two
} The variations
-
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.
Lesson done
Back to Bit Manipulation →Mark it done once you can write the template from memory and you have solved the worked examples yourself.