Tuesday, June 21, 2011

Xor Range without LOOP

HOW to get Xor between numbers from 1 to 300000000
you will get TLE if you try to use Loop for all numbers

I ask this Question on the codeforces site Click Here to see the discussion

jacob answer
Let's introduce
f(x) = x ^ (x-1) ^ (x-2) ^ ... ^ 1
Then anwer would be
f(end) ^ f(start - 1)
Let's now learn to calculate f(x) fast enough. First, notice that f(4*k - 1) = 0 (provable by induction). So to calculate f(x) you only need to take at most 4 last numbers and xor them.
Finally,
f(4*k) = 4*k
f(4*k + 1) = 1
f(4*k + 2) = 4*k + 3
f(4*k + 3) = 0

Expressions "at most 4 last numbers" and "only last 4 numbers" are different. In fact, you need to take exactly (x+1)%4 last numbers.

Conclusion:
Use this function

int f(int n){
switch(n%4){
case 0: return n;
case 1: return 1;
case 2: return n+1;
default: return 0;
}
}
so if you want to get Xor between numbers in range start to end

f(start)^f(end-1)

Friday, April 15, 2011

My First C++ Code in my Blog

for(int i=0;i< 2000000;i++)
{
cout << i << endl;
}