def solution(start, length): checksum = 0 for i in range(length): base = start + length * i checksum ^= calc_checksum_range(base, base + length - i) return checksum # P = [01]* # P^P = 0 # P00^P01^P10^P11 = 0 def calc_checksum_range(_from, _to): # _from included, _to is NOT included checksum = 0 remain = (-_from) % 4 for i in range(_from, min(_from + remain, _to)): checksum ^= i checkpoint = _from + remain remain = _to % 4 for i in range(max(_from, checkpoint, _to - remain), _to): checksum ^= i return checksum tests = [ ([0, 3], 2), ([17, 4], 14) ] for i, o in tests: result = solution(*i) print (i, result == o, result, o)