+ 2

finding lcm in python

Hi friends. Can you please help me ? To practice, I want to write a program to find lcm . But my program has some problems and it doen't have any result. Thank you for helping me correct the problems. number_1 = input("Hello! Please enter your first number: ") number_2 = input("And your second number please? ") i = 1 j = 0 while j != i: n = 1 while j != i: i = number_1 * n n = n + 1 m = 1 while j != i: j = number_2 * m m = m + 1 else: print("lcm",i)

14th Dec 2020, 11:54 AM
Najmeh
Najmeh - avatar
6 Answers
+ 3
I tried to run it too at the same time, but it still does not work because the both numbers are still multiplied by the same number (n) For example: num1 = 10 num2 = 20 n = 1 - - - - - - - - - - - 10 * 1 = 10 20 * 1 = 20 - - - - - - - - - - - 10 * 2 = 20 20 * 2 = 40 - - - - - - - - - - - 10 * 3 = 30 20 * 3 = 60 and so on.. And when this happens, the multiple of two numbers will never meet or intersect cause their gap or difference is getting larger and larger every loop (because they are multiplied by the same number). However, you can use data structures like lists to append every factors and find then print the least common number of both list just like the LCM. - - - - - -Another ways to solve LCM- - - - - - 1. You can solve first the GCD: LCM = (num1 * num2) / GCD 2. You can also use modulo: if x > y: higher_num = x else: higher_num = y if (higher_num % y == 0) and (higher_num % x == 0): print("LCM =", higher_num) else: higher_num += 1 Najmeh I hope I helped somehow😊
14th Dec 2020, 1:07 PM
noteve
noteve - avatar
+ 4
Nicko12 and Ratnapal Shende thank you for devoting your time and helping me
15th Dec 2020, 6:42 AM
Najmeh
Najmeh - avatar
+ 3
First of all, number_1 = int(input("text: ") number_2 = int(input("text: ") But it still doesn't work so wait a second, I'll figure out the rest.
14th Dec 2020, 12:10 PM
noteve
noteve - avatar
+ 3
The problem is that The second "while j != i" will never become True (because it just keeps multiplying the number_1 by n), therefore j and i will never be equal and it will cause an infinite loop and prevents the second "while loop" below it from running.
14th Dec 2020, 12:53 PM
noteve
noteve - avatar
+ 3
# Najmeh you can run two loops simultaneously using multiprocessing module from multiprocessing import Process def loop_a(): while 1: print("a") def loop_b(): while 1: print("b") if __name__ == '__main__': Process(target=loop_a).start() Process(target=loop_b).start() #Stack #Google http://docs.python.org/library/multiprocessing.html
14th Dec 2020, 2:28 PM
Ratnapal Shende
Ratnapal Shende - avatar
+ 2
So how can I run the second and third loops at the same time?
14th Dec 2020, 1:03 PM
Najmeh
Najmeh - avatar