Dart: Multiply without using the multiplication '*' operator

In this challenge, the task is multiplying two numbers without using the multiplication '*' operator. There are many ways to solve this challenge, and we will learn two of them in this article.

Solution 1: Using a loop

This is the most common solution, and we must understand how multiplication works: multiplying a quantity by a number consists of adding that quantity as many times as the number indicates. So, 4×3 is equal to adding the number 4 three times. In code, it can be expressed as:

final result = 4 + 4 + 4;

If we analyze for a moment, we can see that to solve this problem, we need to use a loop. In this case, the best option is a for loop. So, we can create a function called multiply and have something like this:

num multiply(num a, num b) {
  num result = 0;
  for (int i = 0; i < b; i++) {
    result += a;
  }
  return result;
}

However, there is an issue with the above code; it only works if both arguments are positive numbers. We can check if b is negative if we also need to support negative numbers. In that case, instead of adding, we will subtract. The code would look like this:

num multiply(num a, num b) {
  num result = 0;
  bool isNegative = b < 0;

  for (int i = 0; i < b.abs(); i++) {
    result = isNegative ? result - a : result + a;
  }
  return result;
}

We use the b.abs() function in the condition because if b were negative, the condition would always be false. Another thing to note is that we do not check if the variable a is negative because the result is negative when adding two negative numbers.

You can run the code of the first solution in DartPad. Play with the variables to see different results.

Solution 2: Using rules of fractions

For this solution, one must be familiar with the rules of fractions, specifically the following rule:

Rule: a/b/c = ac/b

Rule: a/b/c = ac/b

What is interesting about this rule is when we substitute the value of b with the number 1. Let's do it:

Substitute b with 1

Substitute b with 1

As we can see, the multiplication of a * c is equivalent to a/(1/c). Now, with all this information, our multiplication function would look like this:

num multiply(num a, num c) {
    return a / (1 / c);
}

However, there is an issue with the above code because any number divided by zero will cause an exception in the program. Therefore, if c is zero, we will return 0 as the result. After updating, the code would be as follows:

num multiply(num a, num c) {
    return c == 0 ? 0 : a / (1 / c);
}

You can run the code of the second solution in DartPad. Play with the variables to see different results.

Share this article