Python program to find HCF of Two Numbers

Find HCF of two Numbers

The HCF or the Highest Common Factor of two numbers is the largest common factor of two or more values. The HCF can be calculated using some simple mathematical tricks. The following algorithm will determine how a c program can calculate the HCF of two numbers.

For Example:

60 = 2 * 2 * 3 * 5

72 = 2 * 2 * 2 * 3 * 3

HCF = 2 * 2 * 3

Final Answer = 12

Python program to find HCF of Two Numbers

Working:

Step 1. Start

Step 2. Take two user input and store into int type variable. such as num1 and num2.

Step 3. Create a list name as arr.

Step 4. Now, check if num1 > num2, then store num2 value in smaller variable.

Step 5. Else, Store num1 value in smaller variable.

Step 6.  Run a for loop starts from 1 to smaller+1.

Step 7. Inside the for loop, check num % i == 0 and num2 % i == 0. If both conditions are true then only add element to list.

Step 8. Finally, Print the max element of an array.

Stop 9. Stop

Python Program:

num1 = int(input("Enter first number:"))
num2 = int(input("Enter Second Number:"))
arr = []
if num1 > num2:
    smaller = num2
else:
    smaller = num1
for i in range(1,smaller+1):
    if (num1 % i == 0) and (num2 % i == 0):
        arr.append(i)
print("The HCF of given numbers: {}".format(max(arr)))

# This code is contributed by Shubhanshu Arya (Prepinsta Placement Cell Student) 

Output:

Enter first number:36
Enter Second Number:60
The HCF of given numbers: 12