spd
spd

Reputation: 2134

Division using right shift for divider which not power of 2

I would like to perform the division of num by 60 which is not power of two using right shift operation. How do I do this?

If I want num/64, I can do num >> 6 since 64 = 2^6

How do I do it for 60?

Upvotes: 1

Views: 613

Answers (1)

Justin
Justin

Reputation: 4216

This should work:

public static final long divisionUsingShift(int x, int y) {
    int a, b, q, counter;

    q = 0;
    if (y != 0) {
        while (x >= y) {
            a = x >> 1;
            b = y;
            counter = 1;
            while (a >= b) {
                b <<= 1;
                counter <<= 1;
            }
            x -= b;
            q += counter;
        }
    }
    return q;
}

Upvotes: 2

Related Questions