0

In this code, I am trying to get prime factors for the prime method to find LCM. then I am trying to save it by counter but I am not able to divide both key and values for the proper method. I'm stuck at counter, please can anyone help me?

from collections import Counter

def q2_factor_lcm(a, b): #function for lcm
    fa = factor_list(a)  #factor list for a
    fb = factor_list(b) #factorlist for b
    c = Counter(fa) #variables to save counter for a
    d = Counter(fb) #variables to save counter for b
    r = c | d

    r.keys()
    for key, value in sorted(r.items()): # for loop for getting counter                                                              subtraction
        l = pow(key, value)
        result = []              # I am getting confused what to do now
        for item in l:
            result.append(l)
    return result #will return result

def factor_list(n): # it is to generate prime numbers 
    factors = [] # to save list
    iprimes = iter( primes_list(n) ) # loop
    while n > 1:
        p = next(iprimes)
        while n % p == 0: # python calculation
            n = n // p
            factors.append(p)
    return factors # it will return factors
Vineeth Sai
  • 3,389
  • 7
  • 23
  • 34
Rutvik
  • 11
  • 1

1 Answers1

1

First this method is not really efficient to find a lcm. As there are some nice and clean algo to find a gcd, it is easier to get the lcm of a and b by lcm = a * b / gcd(a,b) (*).

Second, never use pow with integer values. Floating point arithmetics is know to be broken not accurate.

Now for your question. The update operation on the 2 counters in not what you want: you lose one of the values when a key is present in both dicts. You should instead use the union of the key sets, and then use the max of both values (a non existent key is seen as a 0 value for the exponent):

...
# use a true dict to be able to later use the get method with a default
c = dict(Counter(fa)) #variables to save counter for a
d = dict(Counter(fb)) #variables to save counter for b

result = []
for key in sorted(set(c.keys()).union(set(d.keys()))):
    exp = max(c.get(key, 0), d.get(key, 0))
    for i in range(exp):
        result.append(key)
return result

(*) The trick is that when a > b, GCD(a,b) is GCD(b, mod(a,b)). In Python it gives immediately:

def gcd(a, b):
    if b > a:
        return gcd(b, a)
    if b == 1:
        return b
    m = a % b
    return b if m == 0 else gcd(b, m)

def lcm(a,b):
    return a * b / gcd(a,b)
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252