I need help with a program in python 3.3 that is supposed to do Russian peasant multiplication/ancient Egyptian multiplication. The assignment says," If "A" and "B" are the two integers to be multiplied, we repeatedly multiply "A" by 2 and divide "B" by 2, until "B" cannot divide any more and is not zero (integer division). During each set of multiplying "A" and dividing "B", if the value of "B" is an odd number, you add whatever the "A" value is to a total. At the end, the sum of all the "A" values (when "B" is odd) should be equal to the product of the original "A" and "B" inputs. In short, sum up all the "A" values for which "B" is odd and it will be equal (or close) to the product of "A" and "B".
edit
I may have phrased some of the question wrong.
Here is an example:
If "A" is 34, and "B" is 19, multiplying "A" by two and dividing "B" by two each line.
"A" "B"
(34) (19) ("B" is odd, add "A" to total)
(68) (9) ("B" is odd, add "A" to total)
(136) (4) ("B" is even, ignore "A" value)
(272) (2) ("B" is even, ignore "A" value)
(544) (1) ("B" is odd, add "A" to total)
When you sum all the values of "A" for which "B" is odd, you get (34 + 68 + 544 = 646), which is equal to just multiplying "A" and "B", (34 * 19 = 646).
The part I'm having trouble with is adding "A" to a total whenever "B" is an odd number.
This is what I have so far,
x = int(input("What is the first number? "))
y = int(input("What is the second number? "))
answer = 0
while y != 0:
if (y%2 != 0):
x*2
y//2
answer == answer + x
if (y%2 == 0):
x*2
y//2
print("the product is",(answer))
I'm very new to python and programming, so any help and/or explanations of why its wrong would be greatly appreciated.
y
orx
. You need to replacex*2
andy//2
withx = x*2
andy = y//2
respectfully. – Appositionanswer
either. You are testing ifanswer
is equal toanswer + x
. Use a single=
to assign, or better yet, use in-place addition:answer += x
. – Theophany