fornaxx's blog

By fornaxx, history, 6 weeks ago, In English

Result: x % n = x & (n-1), where n is some power of 2 i.e. n = 1 << i.

Why this works?

Lets take an example of 14 % 4,

14 = 1110 = 8(4th-Bit) + 4(3rd-Bit) + 2(2nd-Bit) + 1(1st-Bit)
14 = 8 + 4 + 2 + 0
14 = (4*2) + (4) + 2 + 0

This implies 14 % 4 = (4*3 + 2) % 4 = 2 % 4 = 2 i.e. only the last two bits of 14 contribute to the remainder when dividing by 4. In general, when dividing by 1 << i, only the last i bits of x determine the remainder. This remainder can be computed efficiently with x & (n - 1).

Uses

Though a simple observation, but can be leveraged to solve some interesting variations of problem, try Make Almost Equal With Mod.

Full text and comments »

  • Vote: I like it
  • +15
  • Vote: I do not like it