俄式农民乘法 Python 3.3
我需要帮助,想写一个程序,用Python 3.3实现俄罗斯农民乘法或古埃及乘法。作业要求是:“如果‘A’和‘B’是要相乘的两个整数,我们要不断把‘A’乘以2,同时把‘B’除以2,直到‘B’不能再除下去且不为零(整数除法)。在每次将‘A’乘以2和将‘B’除以2的过程中,如果‘B’是奇数,就把当前的‘A’值加到一个总数里。最后,当‘B’是奇数时,所有‘A’值的总和应该等于原始‘A’和‘B’的乘积。简单来说,就是把所有‘B’为奇数时的‘A’值加起来,结果应该等于(或接近)‘A’和‘B’的乘积。
编辑
我可能把问题表述得不太清楚。
这里有个例子:
如果‘A’是34,‘B’是19,每一行都把‘A’乘以2,把‘B’除以2。
“A” “B”
(34) (19) (“B”是奇数,加入“A”到总数)
(68) (9) (“B”是奇数,加入“A”到总数)
(136) (4) (“B”是偶数,忽略“A”的值)
(272) (2) (“B”是偶数,忽略“A”的值)
(544) (1) (“B”是奇数,加入“A”到总数)
当你把所有‘B’为奇数时的‘A’值加起来,你会得到(34 + 68 + 544 = 646),这正好等于‘A’和‘B’的乘积(34 * 19 = 646)。
我遇到的问题是每当‘B’是奇数时,如何把‘A’加到总数里。
这是我目前的代码:
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))
我对Python和编程非常陌生,所以任何帮助和/或对我代码错误的解释都将非常感激。
5 个回答
顺便提一下,老实说,我直到现在才知道这个算法。让我惊讶的是,古埃及人或者古俄罗斯人居然也用过它。(其实,我更倾向于相信它源于俄罗斯,因为斯拉夫民族似乎和古伊特鲁里亚人有直接的关系。)
这个古老的起源让我感到惊讶,因为它其实就是你在小学学过的简单手工乘法。唯一的不同是,数字首先被转换成了二进制表示。听起来更像是机器在做的事情,不是吗? :)
在这个问题中,34的十进制表示等于二进制的100010,而19的十进制表示等于二进制的10011。现在我们来看看在纸上进行的简单小学乘法:
100010
x 10011
------------
100010 i.e. 100010 times 1
100010 1000100 times 1
000000 10001000 times 0
000000 100010000 times 0
100010 1000100000 times 1
------------ ^ binary digits of the multiplier
1010000110 (reminder of division by 2)
^ adding the zero means multiplying by 2
i.e. sum only when 1 is the reminder of division
看起来设计这个方法的人(在古代)知道什么是二进制数字。
我对你想要实现的算法不太熟悉,不过我对你的代码做了一些修改。
x = int(input("What is the first number? "))
y = int(input("What is the second number? "))
answer = 0
# != 0 is redundant: y is True if it is not 0
while y:
# no need to have parentheses here
if y % 2:
# this needs to be an assignment, not a check for equality
answer += x # shorthand for answer = answer + x
# These happen every time, so does not need to be inside the if
# these also need to be an assignment, not just an expression
x *= 2
y /= 2
# total was never defined
print("the product is", (answer))
你需要先把x加到答案上,然后再更新x。
下面是正确的代码:
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):
answer=answer+x
x=x*2
y=y//2
if (y%2 == 0):
x=x*2
y=y//2
print("the product is",(answer))