Multiplication
Multiplication

Reputation: 27

Multiply two integers without the use of any binary operators

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

Answers (2)

R. Martinho Fernandes
R. Martinho Fernandes

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:

  • Initialize the variable with the constructor-like syntax: no need for the symbol of the assignment operator (just in case someone unknowingly claims that kind of initialization is an assignment);
  • Use increment and decrement instead of adding or subtracting one;
  • Take advantage of implicit conversion of integral types to bool to use in the conditions of the cycles: this way I can compare with 0 with using operators;

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

mrK
mrK

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

Related Questions