Reputation: 27
How to multiply two integers without the use of any binary operators? I know how to do that with recursion, but the recursion would make use of "==".
Upvotes: 0
Views: 720
Reputation: 234424
You can do this for unsigned integers using only the increment and decrement operators:
unsigned x(?), y(?);
unsigned r(0);
while(x--) {
unsigned z(y);
while(z--) {
r++;
}
}
These are the tricks I used above to avoid using binary operators, and still get equivalent effects:
The algorithm works by making the body of inner loop run x * y
times. It's obvious that the outer loop runs x
times. The inner loop always runs y
times, because I took care never to change the value of y
, by copying it into another variable (again, without using the assignment operator). Thus the end result is that r
is incremented x * y
times, giving us the desired result.
Upvotes: 10
Reputation: 2278
Try this:
x * y:
result = 0
while(x--)
while(y--)
result++;
result = (x<0) ? result * -1 : result
result = (y<0) ? result * -1 : result
using help from Martinho
Upvotes: -1