The Highest Common Factor (HCF) or Greatest Common Divisor (GCD) of two integers is the largest integer that can exactly divide both integers (without a remainder).
For example, the HCF of 60 and 72 is 12.
Example 1: Find HCF using for Loop
Output
Enter a first integer: 60 Enter a second integer: 72 HCF of 60 and 72 is 12.
In the above program, the user is prompted to enter two positive numbers.
The for loop is used to iterate from 1 to numbers entered by the user.
The if condition and modulus operator % is used to find the HCF of both numbers.
In the above condition, if both the integers number1 and number2 are exactly divisible by i, the highest integer value that fulfils that condition is calculated.
Example 2: HCF using while Loop and if...else
Output
Enter a first integer: 60 Enter a second integer: 72 HCF is 12
In the above program, a while loop is used with an if...else statement.
In each iteration, the smaller integer is subtracted from the larger integer. And the result is assigned to a variable holding the larger integer.
The while loop continues until both the integers become equal.