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
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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Program to find GCD or HCF of two numbers
- Find HCF of two numbers without using recursion or Euclidean algorithm
- Program to find HCF (Highest Common Factor) of 2 Numbers
- Primality Test | Set 1 (Introduction and School Method)
- Why is programming important for first year or school students?
- Program to find HCF iteratively
- Program to find LCM of 2 numbers without using GCD
- C++ Program for GCD of more than two (or array) numbers
- Java Program for GCD of more than two (or array) numbers
- HCF of array of fractions (or rational numbers)
- Pair of integers having least GCD among all given pairs having GCD exceeding K
- Finding LCM of more than two (or array) numbers without using GCD
- Find two numbers whose sum and GCD are given
- Program to find GCD of floating point numbers
- Find the other number when LCM and HCF given
- Count of triplets of numbers 1 to N such that middle element is always largest
- GCD of two numbers when one of them can be very large
- GCD of two numbers formed by n repeating x and y times
- GCD of more than two (or array) numbers
- GCD of factorials of two numbers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.