Wednesday, March 19, 2014

Divide a number by 3 without using *, /, +, -, % operators

Problem
Divide a number by 3 without using *, /, +, -, % operators
Solution

Method 1 - Divide the number using bitwise operator

We have already discussed how to divide a number by 3 with the help of '+' operator here. So, all we have to do is write a plus operator with the help of bitwise operator, which we have done here.

// replaces the + operator
int add(int x, int y) {
    int a, b;
    do {
        a = x & y;
        b = x ^ y;
        x = a << 1;
        y = b;
    } while (a);
    return b;
}

int divideby3 (int num) {
    int sum = 0;
    while (num > 3) {
        sum = add(num >> 2, sum);
        num = add(num >> 2, num & 3);
    }
    if (num == 3)
        sum = add(sum, 1);
    return sum; 
}


0 comments:

Post a Comment