silent_sky's blog

By silent_sky, history, 5 years ago, In English

Given two integers $$$A$$$ and $$$B$$$, find $$$A$$$ $$$\oplus$$$ $$$($$$ $$$A$$$ $$$+$$$ $$$1$$$ $$$)$$$ $$$\oplus$$$ $$$($$$ $$$A$$$ $$$+$$$ $$$2$$$ $$$)$$$ $$$\oplus$$$ $$$\dots$$$ $$$\oplus$$$ $$$B$$$ where $$$A$$$ $$$<=$$$ $$$B$$$

No, not in linear time

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

| Write comment?
»
5 years ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

You can use a trick, that 1 xor 2 xor .. xor (4 * x — 1) = 0.

And A xor A + 1 xor .. xor B = (1 xor 2 xor .. xor (A — 1)) xor (1 xor 2 .. xor B)

»
5 years ago, # |
  Vote: I like it +1 Vote: I do not like it

The XOR sum of numbers from 1 to m equals:

m   if m%4 is 0
1   if m%4 is 1
m+1 if m%4 is 2
0   if m%4 is 3