pushrbx icon

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

pushrbx | PRO | 09/23/13 09:34:25 PM UTC | 0 ⭐ | 403 👁️ | Never ⏰ | []
C++ |

490 B

|

None

|

0 👍

/

0 👎

// http://stackoverflow.com/questions/11694546/divide-a-number-by-3-without-using-operators
// 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; 
}

Comments