Direct formula for summing XOR

Viewed 9334

I have to XOR numbers from 1 to N, does there exist a direct formula for it ?

For example if N = 6 then 1^2^3^4^5^6 = 7 I want to do it without using any loop so I need an O(1) formula (if any)

12 Answers

How about this?

!(n&1)*n+(n%4&n%4<3)

This works fine without any issues for any n;

unsigned int xorn(unsigned int n)
{

    if (n % 4 == 0)
      return n;
   else if(n % 4 == 1)
       return 1;
   else if(n % 4 == 2)
       return n+1;
  else
       return 0;
}
Related