VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-find-hcf-iteratively/

⇱ Program to find HCF iteratively - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to find HCF iteratively

Last Updated : 9 Feb, 2024

HCF (Highest Common Factor) or GCD (Greatest Common Divisor) of two numbers is the largest number that divides both of them. 

👁 GCD
For example, GCD of 20 and 28 is 4, and GCD of 98 and 56 is 14.

Approach 1:
We have discussed the recursive solution in the below post. Recursive program to find GCD or HCF of two numbers

Below is the iterative implementation of Euclid's algorithm 


Output
12

Time Complexity: O(max(a, b))
Auxiliary Space: O(1)

Approach 2: To find the highest common factor (HCF) of two numbers "a" and "b", start with the input values. Enter a loop while "b" is not Zero. Store "b" in a temporary variable "temp", Update "b" to be the remainder of "a" divided by "b" (b = a % b), Update "a" with "temp". Repeat until "b" becomes Zero. Return the value of "a" as the HCF of the original "a" and "b".

Below is the implementation of Euclid's algorithm


Output
HCF of 60 and 96 is 12

Time Complexity: O(log(min(a, b)))
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: