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
- Create a function hcf.
- Use the def keyword to define the function.
- Pass two parameters i.e. numbers to the function.
- Using an if-else statement check which number is smaller.
- Use for loop with the range function to iterate over numbers from 1 to the smaller number.
- During iteration check whether the iterated number divides both input numbers, if yes then assign that number to the variable.
- After the loop is finished print the output.
- 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
Python function program to create a function with *args as parameters.
Python function program to get the factorial of a given number.
Python function program to get the Fibonacci series up to the given number.
Python function program to get unique values from the given list.
Python function program to get the duplicate characters from the string.