Bits & Math in Python
Chapter 60: Bits & Math
5 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
Binary numbers and bitwise operators
In binary each place is worth twice the place to its right (1, 2, 4, 8, …), so a number is the sum of the places whose switch is on, and the bitwise operators &, |, ^, << and >> work on those switches directly.
Bit tricks: the single number, powers of two, counting bits
A few facts about switches give fast answers: x ^ x is 0 and x ^ 0 is x, so XOR cancels pairs; and n & (n − 1) clears the lowest switch that is on, which counts the 1s and spots powers of two.
GCD, LCM and primes with the sieve
Euclid's rule gcd(a, b) = gcd(b, a % b) shrinks the numbers fast until the remainder is 0, lcm(a, b) = a × b // gcd(a, b), and the sieve of Eratosthenes finds every prime up to n by crossing out the multiples of each prime.
Fast power and remainders
Write the exponent in binary, square the base again and again (base, base², base⁴, base⁸, …), and multiply in the squares whose switch is on, taking the remainder after every multiplication so the numbers stay small.
Bitmask DP: a whole set in one number
Let bit j of an integer mask mean "item j is used"; then dp[mask] is the best answer for exactly that set, and each state grows by adding one more item, mask | (1 << j), so all 2ⁿ sets are solved in order of the numbers.