Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีหา HCF หรือ GCD ด้วย Python

Highest Common Factor (HCF) หรือ Greatest Common Divisor (GCD) ของจำนวนเต็มสองจำนวนขึ้นไป คือจำนวนเต็มบวกที่ใหญ่ที่สุดที่หารจำนวนเหล่านั้นลงตัวโดยไม่มีเศษ ตัวอย่างเช่น GCD ของ 8 และ 12 คือ 4

x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
if x > y:
    smaller = y
else:
    smaller = x
for i in range(1, smaller + 1):
    if (x % i == 0) and (y % i == 0):
        hcf = i
print("The H.C.F. of", x, "and", y, "is", hcf)