Monday, 2 March 2015

Multiply: What if there wasn't a multiply operator?


Introduction

Recently, I was asked to solve a problem:

"Imagine there was no multiply operator in C#. Write a method that multiplies two integers together"

An Almost Solution

Thinking on the spot, my initial solution looked something like this:

internal int Multiply(int p1, int p2)
        {
            var higherVal = 0;
            var lowerVal = 0;
            var result = 0;

            if (p1<= p2)
            {
                lowerVal = p1;
                higherVal = p2;
            }
            else
            {
                lowerVal = p1;
                higherVal = p2;
            }
            
            for (int i = 0; i < lowerVal; i++)
            {
                result += higherVal;
            }

             return result;
        }

Firstly, for performance reasons, I find which is the lowest number between the two values, so that we can reduce the number of loops our function performs.

The loop simply iterates over the lowest value, whilst incrementing the result with the higher value.

Although this is suitable for positive integers, the loop doesn't support negative integers.

A Better Solution

Upon reflection and a suggestion from a fellow developer to use absolute values, I believe I have managed write a more robust solution.

 class Multiplier
    {      
        internal int Multiply(int p1, int p2)
        {
            var absP1 = Math.Abs(p1);
            var absP2 = Math.Abs(p2);

            var result = p1 < p2 ? Calculate(absP1, absP2) : Calculate(absP2, absP1);

            if (p1 < 0 ^ p2 < 0)
            {
                result = result * -1;
            }

            return result;
        }

        private int Calculate(int index, int sum)
        {
            var result = 0;
            for (int i = 1; i <= index; i++)
            {
                result += sum;
            }
            return result;
        }
    }



Math.Abs gives us the absolute value for an integer, which is essentially the distance from a given value to 0. This is useful for finding the positive value from a negative value.

I then use the ternary operator to call the Calculate method depending on which integer is larger. The Calculate method is essentially the same loop code as the previous solution.

And then finally  I use the Exclusive-Or operator to determine whether the result value is postive or negative. This is important due to these examples:

-5 * -6 = 30
 5 * -6 = -30

When both integers that are being multipled are negative then the result will be positive. However, if one integer and ONLY one integer is negative then the result will be negative (See mathematics).

result = result * -1 is a small trick for making a positive number negative.

And there we have it.