(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 " );
}
}
}