How to check if a number is a multiple of 9 using bitwise operators in C

1 Answer

0 votes
#include <stdio.h>
#include <stdbool.h>

bool checkMultipleOf9UsingBitwise(int n) {
    if (n == 0 || n == 9) {
        return true;
    } else if (n < 9) {
        return false;
    } else {
        /* 
            until n becomes either:
                    0 or 9 → return true (it's a multiple of 9)
                    < 9 but not equal to 0 or 9 → return false
        */
        return checkMultipleOf9UsingBitwise((n >> 3) - (n & 7));
    }
}

int main() {
    int num = 72; // 8 * 9

    if (checkMultipleOf9UsingBitwise(num)) {
        printf("The Number is multiple of 9\n");
    } else {
        printf("The Number is not multiple of 9\n");
    }

    return 0;
}


/*
run:

The Number is multiple of 9 

*/

 



answered Oct 25, 2025 by avibootz
...