Sketch out an algorithm for multiplying two positive numbers a and b using this technique.?
Full Question: One way to do multiplication is by repeated addition. For example, 47×2547 \times 2547×25 can be evaluated as 47+47+47+…+4747 + 47 + 47 + \ldots + 4747+47+47+…+47 (25 times). Sketch out an algorithm for multiplying two positive numbers a and b using this technique.
Need to create this into Programming Language- I did this in python wondering if someone can tell me if there's a mistake I'm not seeing?
a = int(input("Enter the multiplicand: "))
b = int(input("Enter the multiplier: "))
result = 0
if b < 0:
count = -b
else:
count = b
while count > 0:
if a == 0:
count = 0
result += a
count -= 1
print(result)
3 Answers
- brilliant_movesLv 71 month ago
Hi, Nathaniel.
The question states "two positive numbers", so there are no negative numbers or zero.
This makes your code very straightforward:
a = int(input("Enter the multiplicand: "))
b = int(input("Enter the multiplier: "))
result = 0
while b > 0:
result += a
b -= 1
print (result)
- EddieJLv 71 month ago
It says to multiply two POSITIVE numbers, so I don't know why you are dealing with the possibility of one of them being negative.
- husoskiLv 71 month ago
That's a good start. Try it with a=5 and b=-4, though. The correct answer is -20, of course, but I get:
Enter the multiplicand: 5
Enter the multiplier: -4
20
>>>
The problem is that when you change the sign of (count), you also need to change the sign on what will be added into (result). A simple fix is to add "a = -a" after the "count = -b" line.
Another option is to add an if statement after the final while loop:
if b < 0:
result = -result
...flipping the result sign after all the repeated addition is done. I think I like this better because it doesn't modify your original input.
A minor issue is that when you multiply 500*500 with this, you'll be testing "if a == 0:" 500 times. You can avoid that by reversing the order of if and while at the end:
if a != 0:
while count > 0:
...same loop body, indented 1 extra level
Now a==0 is only tested once, and no loop iterations are performed when that's true. The (result) variable will still have the initial 0 value.