Adeel Mustafa
Adeel Mustafa

Reputation: 31

algorithm to simulate multiplication by addition (pseudo code)

I'm trying to design an algorithm to simulate multiplication by addition. The input has to be, which can be zero, positive or negative.

if "a" & "b" are two numbers 
than
 if (a)(b)=ab or 2*4=8
than a+a+a+a = ab or 2+2+2+2 =8

I have been given a question to solve and i cant figure it out yet. I've designed the following algorithm/pseudo-code:

  1. if C is a place where we have to store after addition and initially C=0
  2. add C into "a" and store in C (0+2=2)
  3. subtract 1 from "b" and store in "b". (4-1=3)
  4. if "b=0" STOP. otherwise goto step 2.

While this algorithm work when b > 0, it fails if b equals -1 or zero. The algorithm keeps running without ever stopping.

How can I fix my algorithm so it works for negative numbers?

Upvotes: 1

Views: 9834

Answers (2)

Iłya Bursov
Iłya Bursov

Reputation: 24146

Here’s the simplest approach:

int x = 5;
int y = -10;

int mul = 0;
if (x > 0)
    for (int i=0; i<x; i++)
        mul += y;
else
    for (int i=0; i>x; i--)
        mul -= y;
// mul now x*y;

Upvotes: 4

James
James

Reputation: 4681

Here are two simple hints for you.

  1. Check for b=0 before adding the c and a, and replace the conditionnal goto statement at step 4 with an uncoditionnal goto.

  2. Remember that 2*-4 = -(2*4). Therefore, you may check if b is negative very early in your code, and set a variable to -1 if it negative, or +1 if it is positive or null. Then set b to the absolute of itself, and let the code continue just as you wrote it. Then at the very last moment, multiply the sum by that temporary variable. Then you have the correct answer.

I won't give you the resulting pseudo-code, as this really is something you have to do yourself ;) Good luck.

Upvotes: 1

Related Questions