on
Italy
- Get link
- X
- Other Apps
# Python program to find the H.C.F of two input number
# define a function
def hcf(x, y):
"""This function takes two
integers and returns the H.C.F"""
# choose the smaller 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
return
# take input from the user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The H.C.F. of", num1,"and", num2,"is", hcf(num1, num2))
OutputEnter first number: 54 Enter second number: 24 The H.C.F. of 54 and 24 is 6This program asks for two integers and passes them to a function which returns the H.C.F. In the function, we first determine the smaller of the two number since the H.C.F can only be less than or equal to the smallest number. We then use a
for
loop to go from 1 to
that number. In each iteration we check if our number perfectly divides
both the input numbers. If so, we store the number as H.C.F. At the
completion of the loop we end up with the largest number that perfectly
divides both the numbers.
def hcf(x, y):
"""This function implements the Euclidian algorithm
to find H.C.F. of two numbers"""
while(y):
x, y = y, x % y
return x
Here we loop until y becomes zero. The statement x, y = y, x % y
does swapping of values in Python. Click here to learn more about swapping variables in Python. In each iteration we place the value of y in x and the remainder (x % y)
in y, simultaneously. When y becomes zero, we have H.C.F. in x.
Comments
Post a Comment