初中程序GCD
Step 1
和Step 2
中找到。 (如果p是发生pm和p的常见因素
pn timesin m和n分别应该重复min {pm,pn}
倍。)因此,对于数字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重复到最小但我无能为力的说法。请帮忙。
答案 0 :(得分:1)
这是获得所需输出的一种方法:
import functools
def gcd(a,b):
def factArr(x):
list = []
i=2
while i <= x:
if (x % i) == 0:
list.append(i)
x = x/i
i = 2
else:
i = i+1
return list
aArr = factArr(a);
bArr = factArr(b);
print("aArr",aArr,"bArr",bArr)
cArr = []
for v in aArr:
if v in bArr:
cArr.append(v)
bArr.remove(v)
print("cArr",cArr)
return functools.reduce(lambda x, y: x*y, cArr)
gcd(60,24)`
答案 1 :(得分:1)
import numpy as np
from collections import Counter
# Find the prime factors of a integer
def prime_factors(n):
factors = []
i = 2
while n > 1:
if n % i == 0:
factors.append(i)
n /= i
else:
i += 1
return Counter(factors)
# Find prime factors of m and n and multiply their common ones
def Middle(m, n):
fm = prime_factors(m)
fn = prime_factors(n)
cf = fm & fn
return np.prod(list(cf.elements()))
或者您也可以在一个班轮内完成:
def Middle(m, n):
return np.prod(list((prime_factors(m) & prime_factors(n)).elements()))