Reputation: 9
Middle School Procedure GCD
Step 1
and Step 2
. (If p is a common factor occurring pm and
pn timesin m and n, respectively, it should be repeated min{pm, pn}
times.)Thus, for the numbers 60 and 24, we get
60 = 2 . 2 . 3 . 5
24 = 2 . 2 . 2 . 3
gcd(60, 24) = 2 . 2 . 3 = 12.
So using the above instructions, this is what I got so far:
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))
I know the last part is wrong but I have no idea how to fix it. The instructions said something about repeating the f to a minimum but I'm clueless. Please help.
Upvotes: 0
Views: 3910
Reputation: 479
This is one way to get your required output:
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)`
Upvotes: 2
Reputation: 5286
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()))
Or you can also do it in a one liner:
def Middle(m, n):
return np.prod(list((prime_factors(m) & prime_factors(n)).elements()))
Upvotes: 1