Least common multiple
Question:
How to calculate the least common multiple of the numbers x and y, if we know the number z and by the condition x + y = z.
The answer does not work(
z = int(input())
ls = list(range(1, z))
my_ls = []
for i in ls:
if z % i == 0:
my_ls.append((i, z-i))
else:
continue
print(*min(my_ls))
Answers:
You got the first part, the x+y=z, but now you need to find the lcm for each (x,y). This should do the trick:
from math import lcm
print(*min(((i,lcm(i[0],i[1])) for i in my_ls), key=lambda x: x[1]))
This will calculate the lcm for each pair (x,y) you found earlier. It then selects the minimum value. It prints the pair i
and the found lcm(x,y)
.
To just get the 2 numbers, use:
print(*min(((i,lcm(i[0],i[1])) for i in my_ls), key=lambda x: x[1])[0])
Your code only looks at the possible pairs of values of and , but you’re not calculating the least common multiple of those pairs.
However, it is not necessary to really produce all those , pairs. There is a shortcut here. Find out what the least integer divisor is of the given number (greater than 1), and then use that to give the required answer. If there is no such divisor (i.e. the given input is prime), then the answer is −1.
def solve(z):
for div in range(2, int(z ** 0.5) + 1):
if z % div == 0: # found a divisor
return z * (div - 1) // div
return z - 1 # z is prime
print(solve(25)) # 20
The returned number is also the value of that gives this least common multiple, so you also know the value of (i.e. − ).
How to calculate the least common multiple of the numbers x and y, if we know the number z and by the condition x + y = z.
The answer does not work(
z = int(input())
ls = list(range(1, z))
my_ls = []
for i in ls:
if z % i == 0:
my_ls.append((i, z-i))
else:
continue
print(*min(my_ls))
You got the first part, the x+y=z, but now you need to find the lcm for each (x,y). This should do the trick:
from math import lcm
print(*min(((i,lcm(i[0],i[1])) for i in my_ls), key=lambda x: x[1]))
This will calculate the lcm for each pair (x,y) you found earlier. It then selects the minimum value. It prints the pair i
and the found lcm(x,y)
.
To just get the 2 numbers, use:
print(*min(((i,lcm(i[0],i[1])) for i in my_ls), key=lambda x: x[1])[0])
Your code only looks at the possible pairs of values of and , but you’re not calculating the least common multiple of those pairs.
However, it is not necessary to really produce all those , pairs. There is a shortcut here. Find out what the least integer divisor is of the given number (greater than 1), and then use that to give the required answer. If there is no such divisor (i.e. the given input is prime), then the answer is −1.
def solve(z):
for div in range(2, int(z ** 0.5) + 1):
if z % div == 0: # found a divisor
return z * (div - 1) // div
return z - 1 # z is prime
print(solve(25)) # 20
The returned number is also the value of that gives this least common multiple, so you also know the value of (i.e. − ).