tinycodinglm / math /math-0151.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame
1.42 kB
opencode trace
System You are an expert mathematician and programmer.

You are an expert mathematician and programmer.

User

Explain bit manipulation mathematics deeply

Assistant

Popcount: number of set bits. Kernighan: x & (x-1) clears lowest set bit. Loop until x=0 counts bits.

XOR properties: a^a=0, a^0=a, commutative/associative. Missing number in 1..n: XOR all nums and indices. Single number appearing once: XOR all.

Isolate lowest set bit: x & (-x). Highest set bit: 1 << (31 - __builtin_clz(x)).

Bitmasks for subsets: iterate subsets of {0..n-1}: for(mask=0; mask<(1<<n); mask++) for(i=0; i<n; i++) if(mask&(1<<i)).

Subsets of submasks: for(sub=mask; sub; sub=(sub-1)&mask) iterates all non-empty submasks. Total: 3^n over all masks.

Gosper's hack: next number with same popcount. x += x & (-x); x |= (((x & (-x)) / (x & (-x))) >> 1) - 1. Used for iterating subsets of fixed size.

Bit DP: dp[mask] = best value for subset mask. TSP: dp[mask][i] = min cost visiting mask ending at i. O(n^2 * 2^n).

Population count parity: XOR all bits. Useful for parity checks, Gray code conversion.

Bit reversal: for i in 0..n-1: rev[i] = rev[i>>1]>>1 | ((i&1) << (log2n-1)). Used in FFT.