Discussion on the formula for calculating an exclusive or (Memo)

Source: Internet
Author: User

(I am here to discuss the differences orAlgorithmAnd write it down as a memo)

 

To sum up and prove the formula of 1 ^ 2 ^ 3 ^... ^ N:

It is not difficult to prove the following two differences or formulas (we will not prove them here for the sake of simplicity ):
0 ^ n = N
N ^ n = 0

So there are:
1 ^ 2 ^... ^ n = 0 ^ 1 ^ 2 ^... ^ n
That is, if the formula for calculating 0 ^ 1 ^ 2 ^... ^ N is 1 ^ 2 ^... ^ N

Because:
The binary format of 0 ^ 1 ^ 2 ^ 3 is:
0 ^ 1 ^ 10 ^ 11 = 0
4 ^ 5 ^ 6 ^ 7:
100 ^ 101 ^ 110 ^ 111 = 0
(0 ^ 1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 6 ^ 7 = 0)
According to the exclusive or operation rules (0 for the same, 1 for different values) and binary features (01 in binary can be exchanged once every four bits, please test it yourself, 0 ^ 1 ^ 2 ^... ^ in N, a result 0 is displayed every four digits starting from 0.

Assume that the result 0 is obtained when the operation is performed on the I-th digit, that is:
0 ^ 1 ^... ^ I = 0
And
(I + 1) % 4 = 0
That is, as long as (I + 1) % 4 = 0:
0 ^ 1 ^... ^ I = 0
There are:
0 ^ 1 ^... ^ I ^ (I + 1) = I + 1 (because: 0 ^ n = N)

Based on the summary above, the speed calculation method (UseProgramIt indicates that the actual test can improve the efficiency when n is relatively large ):

Code
Public Static   Int Getxorvalue ( Int N ){

If (N % 4 = 0 ) Return N;

If (N < 4 )
{
Int Result = N;
For ( Int I = 1 ; I < N; I ++ )
{
Result = Result ^ I;
}
Return Result;
}
Else
{
Switch (N % 4 )
{
Case   1 :
Return (N - 1 ) ^ N;
Case   2 :
Return (N - 2 ) ^ (N - 1 ) ^ N;
Case   3 :
Return   0 ;
Default :
Throw   New Exception ( " Error " );
}
}
}

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.