Program to find GCD or HCF of two numbers using Middle School Procedure
Given two positive integers M and N, the task is to find the greatest common divisor (GCD) using Middle School Procedure.
Note: GCD of two integers is the largest positive integer that divides both of the integers.
Input: m = 12, n = 14 Output: 2 Prime factor of 12 = 1*2*2*3 Prime factor of 14 = 1*2*7 GCD(12, 14) = 2 Input: m = 5, n = 10 Output: 5 Prime factor of 10 = 1*2*5 Prime factor of 5 = 1*5 GCD(5, 10) = 5
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
The algorithm to find GCD using Middle School procedure GCD(m, n):
- Find the prime factorization of m.
- Find the prime factorization of n.
- Find all the common prime factors.
- Compute the product of all the common prime factors and return it as gcd(m, n).
Below is the implementation of above algorithm:
Prime factor of 10 = 1*2*5 Prime factor of 15 = 1*3*5 GCD(10, 15) = 5