. !
: " XOR , ". , !
, 3-6 3 ^ 4 ^ 5 ^ 6 = 4 O (1) .
:
XOR . , A ^ B ^ C B ^ A ^ C.
, , XOR : ", True i.e 1, 2.
:
XOR 3-6 :
3^4^5^6 = (0^1^2)^(0^1^2) ^ (3^4^5^6)
= (0^1^2^3^4^5^6) ^ (0^1^2) (this comes from the associative nature of xor)
= XOR betn all the numbers from (0-6) ^ XOR betn all the numbers from (0-2)...eq(1)
, XOR 0 , .
, :
. :
(0-1): 0 ^ 1 = 1 (1)
(0-2): 0 ^ 1 ^ 2 = 3 (2+1)
(0-3): 0 ^ 1 ^ 2 ^ 3 = 0 (0)
(0-4): 0 ^ 1 ^ 2 ^ 3 ^ 4 = 4 (4)
(0-5): 0 ^ 1 ^ 2 ^ 3 ^ 4 ^ 5 = 1 (1)
(0-6): 0 ^ 1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 6 = 7 (6+1)
(0-7): 0 ^ 1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 6 ^ 7 = 0 (0)
(0-8): 0 ^ 1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 6 ^ 7 ^ 8 = 8 (8)
So the pattern for finding the xor between all the integers between 0 to n is:
if n%4 == 1 then, answer = 1
if n%4 == 2 then, answer = n+1
if n%4 == 3 then, answer = 0
if n%4 == 0 then answer = n
Therefore, XOR(0-6) becomes 7 (since 6%4 ==2) and XOR(0-2) becomes 3 (since 2%4 ==2)
Therefore, the eq(1) now becomes:
3^4^5^6 = 7 ^ 3 = 4
, - , xor , , / .
python, google:
def answer(start, length):
checkSum = 0
for l in range(length, 0, -1):
checkSum = checkSum ^ (getXor(start + l-1) ^ getXor(start-1))
start = start + length
return checkSum
def getXor(x):
result = [x, 1, x+1, 0]
return result[x % 4]
source
share