From 39a590f339928804481bf5a235bfa55f7ba3f2af Mon Sep 17 00:00:00 2001 From: Os2002-ux <56460932+Os2002-ux@users.noreply.github.com> Date: Thu, 1 Oct 2020 17:28:37 +0530 Subject: [PATCH] Create check binary number is multiple of 3 Program -Check if the given binary number is multiple of 3 or not Algorithm- if the difference sum of difference of even and odd set bits are multiple of 3 then the binary number is divisible by 3. this program uses recursion to check the difference of odd n even place set bits are multiple or not --- CPP/check binary number is multiple of 3 | 46 ++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 CPP/check binary number is multiple of 3 diff --git a/CPP/check binary number is multiple of 3 b/CPP/check binary number is multiple of 3 new file mode 100644 index 0000000..36a9d2d --- /dev/null +++ b/CPP/check binary number is multiple of 3 @@ -0,0 +1,46 @@ +// CPP program to check if n is a multiple of 3 +#include +using namespace std; + +/* Function to check if n is a multiple of 3*/ +int isMultipleOf3(int n) +{ + int odd_count = 0; + int even_count = 0; + + /* Make no positive if +n is multiple of 3 + then is -n. We are doing this to avoid + stack overflow in recursion*/ + if (n < 0) + n = -n; + if (n == 0) + return 1; + if (n == 1) + return 0; + + while (n) { + /* If odd bit is set then + increment odd counter */ + if (n & 1) + odd_count++; + + /* If even bit is set then + increment even counter */ + if (n & 2) + even_count++; + n = n >> 2; + } + + return isMultipleOf3(abs(odd_count - even_count)); +} + +/* Program to test function isMultipleOf3 */ +int main() +{ + int num = 24; + if (isMultipleOf3(num)) + printf("%d is multiple of 3", num); + else + printf("%d is not a multiple of 3", num); + return 0; +}