DAA: Euclid Algorithm

Euclid Algorithm

The Euclid algorithm finds the GCD of two numbers in the efficient time complexity.

To find the GCD of two numbers, we take the two numbers’ common factors and multiply them.

For example :

Let us take two numbers36 and 60, whose GCD is 12.

           36 = 2 * 2 * 3 * 3
           60 = 2 * 2 * 3 * 5 

Basic Euclid algorithm :

The following define this algorithm

  • If we subtract a smaller number from a larger (we reduce a larger number), the GCD doesn’t change. So if we keep repeatedly subtracting the larger of two, we end up with GCD.
  • Instead of subtraction, if we divide the smaller number, the algorithm stops when we find remainder 0.

The approach implementation is shown below -

C++ code:

 #include <bits/stdc++.h>
 using namespace std;
 // This function will return the GCD of a and b
  int gcd(int a, int b)
 {
     if (a == 0)
         return b;
     return gcd(b % a, a);
 }
 int main()
 {
     int a = 10, b = 15;
     cout << "GCD(" << a << ", " << b << ") = " << gcd(a, b) << endl;
     a = 35, b = 10;
     cout << "GCD(" << a << ", "<< b << ") = " << gcd(a, b)<< endl;
     a = 31, b = 2;
     cout << "GCD(" << a << ", " << b << ") = " << gcd(a, b) << endl;
     return 0;
 } 

C code -

 #include <stdio.h>
 int gcd(int a, int b)
 {
     if (a == 0)
         return b;
     return gcd(b % a, a);
 }
 int main()
 {
     int a = 10, b = 15;
     printf("GCD(%d, %d) = %dn", a, b, gcd(a, b));
     a = 35, b = 10;
     printf("GCD(%d, %d) = %dn", a, b, gcd(a, b));
     a = 31, b = 2;
     printf("GCD(%d, %d) = %dn", a, b, gcd(a, b));
     return 0;
 } 

Java code:

 import java.util.*;
 import java.lang.*;
 class Euclid {
  public static int gcd(int a, int b)
     {
         if (a == 0)
             return b;
         return gcd(b % a, a);
     }
 public static void main(String[] args)
     {
         int a = 10, b = 15, g;
         g = gcd(a, b);
         System.out.println("GCD(" + a + " , " + b + ") = " + g);
         a = 35;
         b = 10;
         g = gcd(a, b);
         System.out.println("GCD(" + a + " , " + b + ") = " + g);
         a = 31;
         b = 2;
         g = gcd(a, b);
         System.out.println("GCD(" + a + " , " + b + ") = " + g);
     }
 } 

Output:

 GCD(10, 15) = 5
 GCD(35, 10) = 5
 GCD(31, 2) = 1 

Time complexity: O(Log min(a, b)), where a and b are the numbers

Extended Euclid Algorithm:

The extended algorithm also finds integer coefficients x and y such that:

 ax + by = gcd(a, b)

Examples: 

 Input: a = 30, b = 20
 Output: gcd = 10
         x = 1, y = -1
 (Note that 30*1 + 20*(-1) = 10)
 Input: a = 35, b = 15
 Output: gcd = 5
         x = 1, y = -2
 (Note that 35*1 + 15*(-2) = 5) 

The extended algorithm modifies the results of our gcd using the recursive calls. Assume that x1 and y1 are the values created after recursive call of x and y.  The updated x and y will be:

 x = y1 - ?b/a? * x1
 y = x1 

C++ code:

 #include <bits/stdc++.h>
 using namespace std;
 int gcdExtended(int a, int b, int* x, int* y)
 {
     // Base Case
     if (a == 0) {
         *x = 0;
         *y = 1;
         return b;
     }
     int x1, y1;
     int gcd = gcdExtended(b % a, a, &x1, &y1);
     // Update x and y using results of
     // recursive call
     *x = y1 - (b / a) * x1;
     *y = x1;
     return gcd;
 }
 int main()
 {
     int x, y, a = 35, b = 15;
     int g = gcdExtended(a, b, &x, &y);
     cout << "GCD(" << a << ", " << b<< ") = " << g << endl;
     return 0;
 } 

C code:

 #include <stdio.h>
 int gcdExtended(int a, int b, int *x, int *y)
 {
           // Base Case
           if (a == 0)
           {
                    *x = 0;
                    *y = 1;
                    return b;
           }
           int x1, y1; // To store results of recursive call
           int gcd = gcdExtended(b%a, a, &x1, &y1);
           // Update x and y using results of recursive call
           *x = y1 - (b/a) * x1;
           *y = x1;
           return gcd;
 }
 // Main Function
 int main()
 {
           int x, y;
           int a = 35, b = 15;
           int g = gcdExtended(a, b, &x, &y);
           printf("gcd(%d, %d) = %d", a, b, g);
           return 0;
 } 

Java code:

 import java.util.*;
 import java.lang.*;
 class Euclid
 {
           public static int gcdExtended(int a, int b, int x, int y)
           {
                    // Base Case
                    if (a == 0)
                    {
                              x = 0; y = 1;
                              return b;
                    }
                    int x1=1, y1=1; // To store results of recursive call
                    int gcd = gcdExtended(b%a, a, x1, y1);
                    // Update x and y using results of recursive
                    // call
                    x = y1 - (b/a) * x1;
                    y = x1;
                    return gcd;
           }
 // Main function Program
           public static void main(String[] args)
           {
                    int x=1, y=1;
                    int a = 35, b = 15;
                    int g = gcdExtended(a, b, x, y);
                    System.out.print("gcd(" + a + " , " + b+ ") = " + g);
           }
 } 

Output:

gcd(35, 15) = 5

How does extend Euclid works seen above, x and y are results for inputs a and b,

   a.x + b.y = gcd                      ----(1) 

And x1 and y1 are results for inputs b%a and a

   (b%a).x1 + a.y1 = gcd  

When we put b%a = (b - (?b/a?).a) in above,

we get following. Note that ?b/a? is floor(b/a)

   (b - (?b/a?).a).x1 + a.y1  = gcd

Above equation can also be written as below

   b.x1 + a.(y1 - (?b/a?).x1) = gcd      ---(2)

After comparing coefficients of 'a' and 'b' in (1) and

(2), we get following

   x = y1 - ?b/a? * x1

   y = x1


Related Topics

DAA: KMP Algorithm

KMP ALGORITHM The KMP algorithm is abbreviated as the "Knuth Morris Pratt” algorithm. This algorithm was developed by all of them.  This algorithm searches a pattern of length m in a string...

10 minutes read.

Invert Binary Tree in DAA

Invert Binary Tree: A binary tree is a tree in which each node of the tree contains two children, i.e., left children and right children. Let us suppose we have...

2 minutes read.

DAA: Interpolation Search Algorithm

Interpolation Search Algorithm There is no doubt that binary search is a great algorithm with average time complexity of log n. The feature of discarding one half of the array reduces...

4 minutes read.

DAA: Find the Height or Maximum Depth of a Binary Tree

Find the Height or Maximum Depth of a Binary Tree We have a binary tree structure and we need to find its height. It is defined by the distance from the...

3 minutes read.

DAA: Algorithm of Right View of a Binary Tree

Algorithm of Right View of a Binary Tree The right view of a binary tree is the visible nodes from the right side of the tree. In the given tree, the visible...

5 minutes read.

DAA: Dynamic Programming

Dynamic Programming Introduction The technique of breaking a problem statement into subproblems and using the optimal result of subproblems as an optimal result of the problem statement is known as dynamic programming....

2 minutes read.

DAA: Rabin Karp Algorithm

Rabin Karp Algorithm The Rabin Karp or Karp Rabin algorithm is used to matching a specific pattern in the string. It uses the technique of hashing to match a specific text. There also...

6 minutes read.

DAA: Depth-First Search Algorithm

Depth-first search: DFS is a traversing algorithm of a graph or tree in which one node is taken as arbitrary, and with the help of that arbitrary node, all its...

6 minutes read.

DAA: Application of DFS and BFS

Application of DFS and BFS Depth-first search and breadth-first searches are the most famous algorithms used in daily life and the programming world. Let us now explore each application in which...

3 minutes read.

DAA: Bubble Sort Algorithm on Linked List

Bubble Sort Algorithm on Linked List In this article, we will sort a Link List using the bubble sort technique. Example: Input : 20->30->40->10 Output :10->20->30->40 Input : 20->4->3 Output : 3->4->20 Sorting Technique The bubble sort technique...

4 minutes read.

DAA: Algorithm to Find the Maximum Width of a Tree

Algorithm to Find the Maximum Width of a Tree The width of a binary tree is defined as the maximum number of nodes at a given level. The level having the...

5 minutes read.

DAA: Continuous Tree

Continuous Tree A continuous tree is the one in which the nodes from root to leaf path, the two adjacent node values, have a difference of 1. Input :          3                     /   \                   ...

5 minutes read.

DAA: Breadth First Search (BFS) for a Graph

Breadth First Search (Bfs) For A Graph The algorithm in which all the graph nodes are traversed is known as the breadth-first search algorithm. In this algorithm, we select one node,...

5 minutes read.

DAA: Bottom view of a Binary Tree

Bottom view of a Binary Tree The bottom view of a binary tree is the number of nodes visible when viewed from the bottom. At every horizontal distance, there would be...

3 minutes read.

DAA: Bead Sort Algorithm

Bead Sort Algorithm The bead sort is also known as the gravity sort algorithm. The algorithm is based on the natural phenomena of gravity. The phenomenon is the falling of things...

3 minutes read.

DAA: Density of a Binary Tree Algorithm

The Density of a Binary Tree Algorithm The density of a binary tree is defined as the ratio of the tree’s size to the tree’s height.  The height of the tree is...

2 minutes read.

DAA: Expression Trees

Expression Trees Expression trees are those in which the leaf nodes have the values to be operated, and internal nodes contain the operator on which the leaf node will be performed. Example:...

4 minutes read.

DAA: Binary Tree and its Categories

Binary Tree and its Categories The binary tree is a non-linear data structure in which there are 0 or utmost 2 nodes.  Each node has two children, i.e., left and right...

4 minutes read.

Boyer Moore Algorithm

Boyer Moore Algorithm The Boyer Moore algorithm is a searching algorithm in which a string of length n and a pattern of length m is searched. It prints all the occurrences...

11 minutes read.

Recurrence relation in DAA

Recurrence relation in DAA The model that uses mathematical concepts to calculate the time complexity of an algorithm is known as the recurrence relational model. A recursive relation, T(n), is a recursive...

5 minutes read.