Python

Python Program to Find HCF or GCD2 min read

Write a program to Find HCF or GCD in Python

Code:




This Python program finds the highest common factor (HCF) of two input numbers.

The program defines a function computeHCF(x, y) that takes two numbers as arguments and returns their HCF. The function starts by determining which of the two numbers is smaller and assigns it to the variable smaller. Then, the function uses a for loop to iterate through the range of numbers from 1 to the smaller number.

In each iteration, the function checks if the current number is a common factor of both x and y by using the modulo operator (%) to check if the remainder of both x divided by the current number and y divided by the current number is zero. If both conditions are true, the current number is assigned to the variable hcf.

Finally, the function returns the value of hcf.

The main program then prompts the user to enter two numbers and assigns them to the variables num1 and num2. Then it calls the computeHCF(num1, num2) function and prints out the HCF of the two numbers entered.

For example, if the user enters the numbers 12 and 16, the output would be:

Leave a Comment