From 07a9944f414affbe7c559d77408b22548825229b Mon Sep 17 00:00:00 2001 From: theSoberSobber <109434814+theSoberSobber@users.noreply.github.com> Date: Sun, 3 Nov 2024 15:53:45 +0530 Subject: [PATCH] Xor-Of-First-N-Natural-Numbers --- codes/Xor-Of-First-N-Natural-Numbers.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 codes/Xor-Of-First-N-Natural-Numbers.cpp diff --git a/codes/Xor-Of-First-N-Natural-Numbers.cpp b/codes/Xor-Of-First-N-Natural-Numbers.cpp new file mode 100644 index 0000000..6b23ed5 --- /dev/null +++ b/codes/Xor-Of-First-N-Natural-Numbers.cpp @@ -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/