An XOR value between n integers of 1 to N (O (1) algorithm)

Source: Internet
Author: User

problem: Ask 1 to the N it N an XOR value between integers, i.e. 1 XOR 2 xor 3 ... xor n

Record f (x, Y) as the XOR value of all integers x through Y.

To f (2^k, 2^ (k+1)-1) (note that the ^ in the article represents "power", Xor means "XOR", or "or"):

2^k to 2^ (k+1)-1 This 2^k number, the highest bit (+k bit) of 1 number is 2^k,

If K >= 1, then the 2^k is even, the highest bit of the 2^k number (+k bit) is removed, the difference or value is unchanged.

Thus F (2^k, 2^ (k+1)-1) = f (2^k-2^k, 2^ (k+1) -1-2^k) = f (0, 2^k-1)

Thus f (0, 2^ (k+1)-1) = f (0, 2^k-1) XOR F (2^k, 2^ (k+1)-1) = 0 (k >= 1)

i.e. f (0, 2^k-1) = 0 (k >= 2)

The highest bit 1 for f (0, N) (n >= 4) is set at the +k bit (k >= 2),

F (0, N) = f (0, 2^k-1) XOR F (2^k, N) = f (2^k, N)

2^k to n this n+1-2^k number, the highest bit (+k bit) Total M = n+1-2^k 1, remove the highest bit of 1

When n is odd, M is an even number, thus f (0, N) = f (2^k, N) = f (0, N-2^k)

Due to the n-2^k and N parity, recursion above formula, can get: F (0, N) = f (0, n% 4)

When n% 4 = = 1 o'clock, f (0, N) = f (0, 1) = 1

When n% 4 = = 3 o'clock, f (0, N) = f (0, 3) = 0

When n is even, M is odd, thus f (0, N) = f (2^k, N) = f (0, n-2^k) or 2^k

That is, the highest bit 1 remains the same, due to the n-2^k and N parity, recursion above the formula,

Available: F (0, N) = NN or f (0, N 4) (minimum 2 position of nn n = 0)

When n% 4 = = 0 o'clock, f (0, n) = n

When n% 4 = = 2 o'clock, f (0, N) = NN or 3 = n + 1 (Formula pair n = 2 is still true)

Sum up:

F (1, N) = f (0, N) =

n N% 4 = = 0

1 n% 4 = = 1

N +1 n% 4 = = 2

0 n% 4 = = 3

Code:

unsigned xor_n(unsigned n)

{

unsigned t = n & 3;

if (t & 1) return t / 2u ^ 1;

return t / 2u ^ n;

}

An XOR value between n integers of 1 to N (O (1) algorithm)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.