การพิมพ์ LCM โดยใช้ for และ while ใน Python

Apr 17 2023
ช่วยพัฒนาความเข้าใจที่ดีขึ้นของลูป อย่างไรก็ตาม เราสามารถคำนวณ LCM โดยใช้ไลบรารีคณิตศาสตร์ใน python ได้เสมอ (วิธีที่ง่ายที่สุด)

#LCM with for loop
a= 15
b = 10
lcm = 1
for i in range(a*b, max(a,b)-1,-1): # Maximum limit of LCM is product of numbers,and minimum limit will greater number of given two number
    if ((i%a) == (i%b)):
        lcm=i                       # Here i is dscreasing from a*b to max(a,b) thus we get lowest which is multiple of both numbers.
print(lcm)
#LCM with while loop
a= 15
b = 10
lcm = max(a,b)
i = a*b                             # maximum limit of i has been set.
while i>= max(a,b):
    if ((i%a) == (i%b)):
        lcm = i
    i-=1                            # Here i is dscreasing from a*b to max(a,b) thus we get lowest which is multiple of both numbers.
print(lcm)

ช่วยพัฒนาความเข้าใจที่ดีขึ้นของลูป

อย่างไรก็ตาม เราสามารถคำนวณ LCM โดยใช้ไลบรารีคณิตศาสตร์ใน python ได้เสมอ (วิธีที่ง่ายที่สุด)