当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Easier + Optimum way of doing binary division

问题描述:

Can anyone suggest what is the most straightforward + optimum way of doing binary division without using recursion in Java?

I have the following code which even though works fine but I believe this basic Maths function should be much more easier here.

private static int div(int dividend, int divisor) {

int denom = divisor;

int count = 1;

while (denom <= dividend) {

denom <<= 1;

count <<= 1;

}

if (denom > dividend) {

denom >>= 1; count >>= 1;

}

int answer = 0;

// Now find the smaller dividend

while (count != 0) {

if (dividend >= denom) {

dividend = dividend - denom;

// Consume the count value;

answer = answer + count;

}

count >>>= 1;

denom >>= 1;

}

return answer;

}

网友答案:

The short answer is that division is kind of a difficult algorithm to implement.

The algorithm you outline above is produces one bit per iteration and (as dividers go) it's fairly simple.

There are other algorithms that also produce 1 bit per iteration (e.g., CORDIC and binary restoring). None of them is a one or two liner, but you might find one of them a little simpler and more understandable.

There are other divider algorithms that can produce more bits per iteration. For example, an SRT radix-4 divider can produce 4 bits per iteration. The expense is that the algorithm is even more complex. If you're having difficulty with the algorithm you gave, my immediate guess is that you'd find these somewhere between hideous and utterly hopeless.

网友答案:

Your intuition is correct; there is a one-liner for this:

private static int div(int dividend, int divisor) {
  return dividend / divisor;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: