Python function program to find the HCF of two numbers

In this python function program, we will find the HCF of two numbers.

HCF:
HCF stands for Highest Common Factor. HCF of two or more numbers is the greatest factor that divides the numbers.

What is Function?
It is a block of code that executes when it is called.
To create a function use def keyword.

Steps to solve the program
  1. Create a function hcf.
  2. Use the def keyword to define the function.
  3. Pass two parameters i.e. numbers to the function.
  4. Using an if-else statement check which number is smaller.
  5. Use for loop with the range function to iterate over numbers from 1 to the smaller number.
  6. During iteration check whether the iterated number divides both input numbers, if yes then assign that number to the variable.
  7. After the loop is finished print the output.
  8. Take two numbers as input through the user and pass them to the function while calling the function.
				
					def hcf(num1,num2):
    if num1 > num2:
        smaller = num2
    else:
        smaller = num1

    for i in range(1, smaller+1):
        if((num1 % i == 0) and (num2 % i == 0)):
            hcf = i

    print(f"H.C.F of {num1} and {num2}: {hcf}")
    
num1 = int(input("Enter number 1: "))
num2 = int(input("Enter number 2: "))
hcf(num1,num2)
				
			

Output :

				
					Enter number 1: 24
Enter number 2: 54
H.C.F of 24 and 54: 6
				
			

Related Articles

calculate the sum of numbers from 0 to 10.

create a function with *args as parameters.

Leave a Comment