9.1k views
0 votes
Martian integer multiplication works as follows (on paper): 1. Write the two integers to be multiplied side by side, at the top of two columns. 2. Divide the number on the left by 2, ignoring any remainder, and double the number on the right. 3. Repeat step 2 for the newly-created numbers, until the number on the left reaches 1. 4. Each time you divide, if the number on the left of that row is odd, add the number on the right to your total. 5. When you are done, the total will be equal to the product of the original two numbers.

1 Answer

4 votes

Answer and Explanation:

def martian(left, right):

if left%2==1:

num=1

else:

num=0

while left!=1:

left//=2

if left%2==1:

num+=1

return num

if __name__ == "__main__":

print('martian(22, 4) is', martian(22,4))

print()

print('martian(15, 2) is', martian(15,2))

print()

print('martian(103, 5) is', martian(103,5))

print()

print('martian(768, 21) is', martian(768,21))

print()

print()

output:

martian(22, 4) is 3

martian(15, 2) is 4

martian(103, 5) is 5

martian(768, 21) is 2

User Tonsic
by
5.1k points