【发布时间】:2017-11-02 22:47:00
【问题描述】:
中学程序GCD
- 第 1 步求 m 的质因数。
- 第 2 步求 n 的质因数。
- 步骤 3 确定两个素数展开式中的所有公因数
在
Step 1和Step 2中找到。 (如果 p 是 pm 和 pn 次在 m 和 n 中分别重复 min{pm, pn} 次。) - 步骤 4 计算所有公因子的乘积并将其返回为 给定数字的最大公约数。
因此,对于数字 60 和 24,我们得到
60 = 2 . 2 . 3 . 5
24 = 2 . 2 . 2 . 3
gcd(60, 24) = 2 . 2 . 3 = 12.
所以使用上面的说明,这是我到目前为止得到的:
import numpy as np
#find prime factors of m and output it to list fm
def Middle(m,n):
c = 2
fm = [ ]
while m > 1:
if m % c == 0:
fm.append(c)
m = m/c
else:
c = c + 1
return fm
#find prime factors of n and output it to list fn
d = 2
fn = [ ]
while n > 1:
if n % d == 0:
fn.append(d)
n = n/d
else:
d = d + 1
return fn
#compare fm and fn and multiply common items
#this is the part where I got wrong
cf = []
for f in fm:
if f in fn:
cf.append(f)
return (np.prod(cf))
我知道最后一部分是错误的,但我不知道如何修复它。说明中提到了将 f 重复到最低限度,但我一无所知。请帮忙。
【问题讨论】:
-
请修正你的代码缩进 - 严重缩进的 Python 代码对读者和 Python 解释器都毫无意义。
-
如果您要明确存储具有多重性的因子会更容易。如果 fm 中有一个多重因子在 fn 中只有一个,那么它与 cf 中的 fm 的多重性一起使用,而它应该只有多重性。
-
由于
fn中出现的任何一个因素f可能只计算一次,所以您只需在找到f时删除它(在cf.append(f)之后添加fn.remove(f))
标签: python algorithm greatest-common-divisor