To understand this example, you should have the knowledge of following Python programming topics:
The highest common factor (H.C.F) or greatest common divisor (G.C.D) of two numbers is the largest positive integer that perfectly divides the two given numbers. For example, the H.C.F of 12 and 14 is 2.
# Python program to find the H.C.F of two input number # define a function def computeHCF(x, y): # 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 hcf num1 = 54 num2 = 24 # 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", computeHCF(num1, num2))
Output
The H.C.F. of 54 and 24 is 6
Here, two integers stored in variables num1 and num2 are passed 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.
The above method is easy to understand and implement but not efficient. A much more efficient method to find the H.C.F. is the Euclidean algorithm.
This algorithm is based on the fact that H.C.F. of two numbers divides their difference as well.
In this algorithm, we divide the greater by smaller and take the remainder. Now, divide the smaller by this remainder. Repeat until the remainder is 0.
For example, if we want to find the H.C.F. of 54 and 24, we divide 54 by 24. The remainder is 6. Now, we divide 24 by 6 and the remainder is 0. Hence, 6 is the required H.C.F.
def computeHCF(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 computeHCF(300, 400)
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.
It takes a lot of effort and cost to maintain Programiz. We would be grateful if you support us by either:
Disabling AdBlock on Programiz. We do not use intrusive ads.
or
Donate on Paypal