[Solved] How to simulate multiplication by addition java


The code you have:

sum = 0;
while (sum < a + b) { 
    sum += a; 
}

will only add a to the sum until the sum becomes a + b. You would need to use a * b in the while loop in that case but, as stated, you’re not allowed to.


Since multiplication is just repeated addition, you can do it with the following (pseudo-) code:

a = 5; b = 4

product = 0
acopy = a
while acopy > 0:
    product = product + b
    acopy = acopy - 1

That’s the basic idea though it has a rather nasty bug for negative numbers.

If you want to handle that as well, you’d need something like:

product = 0
acopy = a
while acopy < 0:
    product = product - b
    acopy = acopy + 1
while acopy > 0:
    product = product + b
    acopy = acopy - 1

Only one of those while loops will run, depending on whether a is negative or positive (if it’s zero, neither will run).

6

solved How to simulate multiplication by addition java