finding the LCM using python - python

def multiple(a, b):
"""so I'm trying to return the smallest number n that is a multiple of both a and b.
for example:
multiple(3, 4)
12
multiple(14, 21)
42
"""
def gcd (a,b):
if a < b : a , b = b,a
while b:
a , b = b , a % b
return a
def lcm (a , b):
n= (a*b) / gcd(a,b)
return n
it keeps throwing errors about indentation and logic. I don't understand why. I've tried changing the variables around too.

No need to find GCD, we can directly find LCM. Below code works
def lcmof(x,y):
res=0
mx=max(x,y)
mn=min(x,y)
for i in range(1,mx+1,1):
temp=mx*i
try:
if(temp%mn==0):
res=temp
break
except ZeroDivisionError:
res=0
break
return res

Related

Unable to crack Python code for GCD of 3 numbers?

I am trying to find the GCD of 3 numbers but have been unable to get around much success till now. I am using the following code
def gcd(a, b,c):
if sum(np.array(list([a,b,c]))%min(a,b,c))==0:
return min(a,b,c)
else:
x = np.array(list([a,b,c]))%min(a,b,c)
if sum((list([x]))%min(x))==0:
return min(x)
When I run this on an example say gcd(21,45,60), it gives me the below error
C:\Users\mmt8091\Anaconda3\lib\site-packages\ipykernel_launcher.py:6: RuntimeWarning: divide by zero encountered in remainder
What am i doing wrong here? Have been unable to find any other solutions on net as well. Please help
You do not need np.
Try this:
def gcd(*args):
a, b, *c = args
a, b = min(a, b), max(a, b)
gcd1 = b if not a else gcd(b % a, a)
for i in c:
gcd1 = gcd(gcd1, i)
return gcd1
print(gcd(21, 45, 60))

Least Common Multiple of 2 numbers by prime factors of number

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
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)

How can i have GCD of two numbers from a recursive functions?

Can we have GCD of two numbers from a recursive functions?
Like a and b
def recursive_f_gcb(a,b):
def recursive_f_gcd(a, b):
if b==0:
return a
else:
return recursive_f_gcd(b, a%b)
a=18
b=12
print(recursive_f_gcd(a, b))
You can follow this process :
def gcd(a,b):
if b > a:
return gcd(b,a)
r = a%b
if r == 0:
return b
return gcd(r,b)
Shorter using a conditional expression
def recursive_f_gcd(a, b):
return a if not b else recursive_f_gcd(b, a%b)
a = 24
b = 18
print(recursive_f_gcd(a, b))
Output:
6

Python GCD - errors

I have an issue with my code whose purpose is to find the GCD of two inputs. When I try to run the module it tells me that 'gcd' is not defined.
def GCD(12,4):
gcd = 1
for i in range(2, max(12,4)/2):
if((12 % i == 0) and (4 % i == 0)):
gcd = i
return gcd
You are not calling the GCF function. You have just defined your function. You need to add a line
gcf = GCF(a,b)
after the place where you accept the input. That is after b = int(input('denomenator: '))
Edit:
Change the input statements to
a = float(input('numerator: '))
b = float(input('denomenator: '))
You can use Euclid division algorithm to find gcd in less time.
Take floating point numbers to a and b.
def gcd(a,b):
c = 1
a,b = max(a,b),min(a,b)
while c != 0:
c = a%b
a,b = b,c
return a
print gcd(12,5)

Python programming beginner difficulties

I am trying to write a program in Python, but I am stuck in this piece of code:
def function():
a=[3,4,5,2,4]
b=1
c=0
for x in range(5):
if a[x-1]>b:
c=c+1
return c
print(function())
It gives me value 1 instead of 5. Actually the function I am trying to write is a little bit more complicated, but the problem is actually the same, it doesn't give me the right result.
def result():
r=[0]*len(y)
a=2
b=an_integer
while b>0:
for x in range(len(y)) :
if y[x-1] > 1/a and b>0:
r[x-1]=r[x-1]+1
b=b-1
a=a+1
return r
print(result())
v is a list of values smaller than 1 and b has an integer as value. If some values x in v are bigger than 1/a then the values x in r should get 1 bigger, then it should repeat a=a+1 until b becomes 0. I want this function to give a result of the type for ex. [7,6,5,4,3] where the sum of the elements in this list is equal to b.
Sometimes it gives me the right value, sometimes not and when the elements in v are equal for example v=[0.33333,0.33333,0.33333] it gets stuck and doesn't give me a result.
I don't know what I am doing wrong !
Your return statements are incorrectly indented. You want to return after the loop ends, not inside the loop.
def function():
a = [3, 4, 5, 2, 4]
b = 1
c = 0
for x in range(5):
if a[x-1] > b:
c = c + 1
return c
Also, a couple of optimizations to the code:
def function(a, b):
c = 0
for x in a:
if x > b:
c += 1
return c
or further:
def function(a, b):
return sum(x > b for x in a)
return; only inside the fun in the end it.
and name the Variable v

Categories

Resources