Evaluate the variance or value between the N integers 1 to n (O (1) algorithm)

Source: Internet
Author: User

Question: Please1ToNThisNThe exclusive OR value between integers, that is1 XOR 2 XOR 3... XOR n

 

NoteF (x, y)IsXToYAll integers.

 

PairF (2 ^ K, 2 ^ (k + 1)-1 )(Note:ArticleIn^Indicates the "power ",XORIt indicates "different or ",Or"Or"):

2 ^ KTo2 ^ (k + 1)-1This2 ^ KNumber, the highest bit (+ KBit)1The number is2 ^ K,

IfK> = 1, Then2 ^ KIs an even number.2 ^ KMaximum number of digits(+ KBit)Remove the value. The value or value remains unchanged.

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

ThereforeF (0, 2 ^ (k + 1)-1) = f (0, 2 ^ k-1) xor f (2 ^ K, 2 ^ (k + 1) -1) = 0 (k> = 1)

That is F (0, 2 ^ k-1) = 0 (k> = 2)

 

PairF (0, n)(N> = 4)SetNThe highest bit1Yes+ KBit(K> = 2),

F (0, n) = f (0, 2 ^ k-1) xor f (2 ^ k, n) = F (2 ^ k, n)

Pair2 ^ KToNThisN + 1-2 ^ KNumber, highest bit(+ KBit)TotalM = n + 1-2 ^ KItems1,Remove the highest bit1

 

WhenNIf it is an odd number,MIs an even number, soF (0, n) = F (2 ^ k, n) = f (0, N-2 ^ K)

BecauseN-2 ^ KAndNFor parity, the formula above is recursive and can be obtained as follows:F (0, n) = f (0, N % 4)

WhenN % 4 = 1, F (0, n) = f (0, 1) = 1

WhenN % 4 = 3,F (0, n) = f (0, 3) = 0

 

WhenNIf it is an even number,MIs an odd number, soF (0, n) = F (2 ^ k, n) = f (0, N-2 ^ K) or 2 ^ K

That is to say, the highest bit1Remain unchanged becauseN-2 ^ KAndNSame as parity, recursive formula above,

Available:F (0, n) = nn or F (0, N % 4) (NNIsNThe lowest2Location0)

WhenN % 4 = 0,F (0, n) = N

WhenN % 4 = 2,F (0, n) = nn or 3 = n + 1(Formula pairN = 2Still valid)

 

To sum up:

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

N % 4 = 0

1 N % 4 = 1

N + 1 N % 4 = 2

0 n % 4 = 3

 

Code:

UnsignedXor_n(UnsignedN)

{

unsigned T = n & 3 ;

If ( T & 1 ) return T / 2u ^ 1 ;

 ReturnT/ 2u ^N;

}

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.