Open In App
Related Articles

C Program for Basic Euclidean algorithms

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

GCD of two numbers is the largest number that divides both of them. A simple way to find GCD is to factorize both numbers and multiply common factors.
 

C

// C program to demonstrate Basic Euclidean Algorithm
#include <stdio.h>
 
// Function to return gcd of a and b
int gcd(int a, int b)
{
    if (a == 0)
        return b;
    return gcd(b % a, a);
}
 
// Driver program to test above function
int main()
{
    int a = 10, b = 15;
    printf("GCD(%d, %d) = %d\n", a, b, gcd(a, b));
    a = 35, b = 10;
    printf("GCD(%d, %d) = %d\n", a, b, gcd(a, b));
    a = 31, b = 2;
    printf("GCD(%d, %d) = %d\n", a, b, gcd(a, b));
    return 0;
}

                    

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

 

Time Complexity: O(Log min(a, b)) 

Auxiliary Space: O(1)
Please refer complete article on Basic and Extended Euclidean algorithms for more details!
 


Last Updated : 05 Nov, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads