Multiples of 4 ( An Interesting Method ) | An interesting XOR based method to check if a number is multiple of 4. ; Returns true if n is a multiple of 4. ; Find XOR of all numbers from 1 to n ; If XOR is equal n , then return true ; Driver code to print multiples of 4 ; Printing multiples of 4 using above method
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isMultipleOf4 ( int n ) { if ( n == 1 ) return false ; int XOR = 0 ; for ( int i = 1 ; i <= n ; i ++ ) XOR = XOR ^ i ; return ( XOR == n ) ; } int main ( ) { for ( int n = 0 ; n <= 42 ; n ++ ) if ( isMultipleOf4 ( n ) ) cout << n << " ▁ " ; return 0 ; }