Q:

Python Program to Find HCF

belongs to collection: Python Function Programs

0

In the following tutorial, we will understand how to find Highest Common Factor (HCF) in the Python programming language.

But before we get started, let us briefly discuss about HCF.

HCF: Highest Common Factor

Highest Common Factor or Greatest Common Divisor of two or more integers when at least one of them is not zero is the largest positive integer that evenly divides the numbers without a remainder. For example, the GCD of 8 and 12 is 4.

For example:

We have two integers 8 and 12. Let's find the HCF.

The divisors of 8 are:

1, 2, 4, 8  

The divisors of 12 are:

1, 2, 3, 4, 6, 12  

HCF /GCD is the greatest common divisor. So HCF of 8 and 12 are 4.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

# defining a function to calculate HCF  
def calculate_hcf(x, y):  
    # selecting 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  
  
# taking input from users  
num1 = int(input("Enter first number: "))  
num2 = int(input("Enter second number: "))  
# printing the result for the users  
print("The H.C.F. of", num1,"and", num2,"is", calculate_hcf(num1, num2))  

Output:

Enter first number: 8
Enter second number: 12
The H.C.F. of 8 and 12 is 4

Explanation:

In the above snippet of code, two integers stored in variable num1 and num2 are passed to the calculate_hcf() function. The function calculates the HCF these two numbers and returns it.

Within the function, we have to determine the smaller number as the HCF can only be less than or equal to the smallest number. We have then used a for loop in order go from 1 to that number.

In every iteration, we have to check if the number perfectly divides both the input numbers. If it does, we have to stored the number as HCF. At the loop completion, we end up with the largest number that perfect divides both the numbers

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Program to Convert Decimal to Binary, Octal... >>
<< Python Program to Find LCM...