Skip to content

Commit

Permalink
Xor-Of-First-N-Natural-Numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
theSoberSobber authored Nov 3, 2024
1 parent 9b7be82 commit 07a9944
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions codes/Xor-Of-First-N-Natural-Numbers.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
//Xor of first N Natural Numbers
//based on the fact that if n%4==3 then xor till n from 1 is 0

auto xorOfFirstN = [&](int n) -> int {
// n%4 = 3 => xor = 0
int t = n, ans = 0;
while(t%4!=3) ans^=t, --t;
return ans;
};

// more explicit version
int computeXOR(int n) {
if (n % 4 == 0) return n;
if (n % 4 == 1) return 1;
if (n % 4 == 2) return n + 1;
return 0;
}

// source: https://www.geeksforgeeks.org/calculate-xor-1-n/

0 comments on commit 07a9944

Please sign in to comment.