Reputation: 31
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:
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
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
Reputation: 4681
Here are two simple hints for you.
Check for b=0 before adding the c and a, and replace the conditionnal goto statement at step 4 with an uncoditionnal goto.
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