C Program To Find GCD of Two Numbers using Recursion: Euclid’s Algorithm

Lets write a C program to find GCD(Greatest Common Divisor) or HCF(Highest Common Factor) of two positive integer numbers input by the user using Euclid’s Algorithm and by using Recursive function call logic.

Related Read:
C Program To Find GCD and LCM of Two Numbers using Euclidean algorithm
Recursive Functions In C Programming Language

Euclid’s Algorithm Logic

If user inputs 2 numbers n1 and n2, reduce the bigger number by modulo dividing it by the smaller number. For example, if n1 is greater than n2, then reduce the value of n1 by replacing it with n1%n2.

Assume that we’ve a function gcd() which returns gcd of 2 numbers passed to it. Ex: gcd(n1, n2);

According to Euclid’s Algorithm, we’ll get the same gcd if we reduce the bigger number by modulo dividing it by smaller number.

If n1 > n2 we need to pass gcd(n1%n2, n2);
If n2 > n1, we need to pass gcd(n1, n2%n1);

We need to recursively execute above 2 lines of logic until either n1 is 0 or until n2 is 0. If n1 is 0, then value present in n2 is the gcd of (n1,n2). If n2 is 0, then value present in n1 is the gcd of (n1,n2).

Video Tutorial: C Program To Find GCD of Two Numbers using Recursion: Euclid’s Algorithm


[youtube https://www.youtube.com/watch?v=k6zrTKpSg20]

YouTube Link: https://www.youtube.com/watch?v=k6zrTKpSg20 [Watch the Video In Full Screen.]


Source Code: C Program To Find GCD of Two Numbers using Recursion: Euclid’s Algorithm

#include<stdio.h>

int gcd(int, int);

int main()
{
    int num1, num2;

    printf("Enter 2 positive integer numbers\n");
    scanf("%d%d", &num1, &num2);

    printf("\nGCD of %d and %d is %d.\n", num1, num2, gcd(num1, num2));

    return 0;
}

int gcd(int n1, int n2)
{
    if(n1 == 0) return n2;
    if(n2 == 0) return n1;

    if(n1 > n2)
        return gcd(n1%n2, n2);
    else
        return gcd(n1, n2%n1);
}

Output 1:
Enter 2 positive integer numbers
1980
1617

GCD of 1980 and 1617 is 33.

Output 2:
Enter 2 positive integer numbers
15
20

GCD of 15 and 20 is 5.

Example:

Lets assume that user has entered n1 = 1980 and n2 = 1617

n1n2Biggest NoEvaluateFunction Call
198016171980gcd(1980 % 1617, 1617)gcd(363, 1617)
36316171617gcd(363, 1617 % 363)gcd(363, 165)
363165363gcd(363 % 165, 165)gcd(33, 165)
33165165gcd(33, 165 % 33)gcd(33, 0)

In above table gcd(33, 0) gets called, since n2 = 0, our program returns value of n1 as gcd, which is 33.

So GCD of 1980 and 1617 is 33.

Source Code: C Program To Find GCD of Two Numbers using Recursion and Ternary or Conditional Operator: Euclid’s Algorithm

#include<stdio.h>

int gcd(int, int);

int main()
{
    int num1, num2;

    printf("Enter 2 positive integer numbers\n");
    scanf("%d%d", &num1, &num2);

    printf("GCD of %d and %d is %d.\n", num1, num2, gcd(num1, num2));

    return 0;
}

int gcd(int n1, int n2)
{
    if(n1 == 0) return n2;
    if(n2 == 0) return n1;

    return( (n1 > n2) ? gcd(n1%n2, n2) : gcd(n1, n2%n1) );
}

Output 1:
Enter 2 positive integer numbers
1980
1617

GCD of 1980 and 1617 is 33.

Know more about ternary operator or conditional operator, watch a separate video tutorial: Ternary Operator / Conditional Operator In C.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Find GCD using Repeated Subtraction

Lets write a C program to find Greatest Common Divisor of two positive integer numbers using repeated subtraction.

Related Read:
C Program to Find GCD or HCF of Two Numbers
C Program To Find GCD and LCM of Two Numbers using Euclidean algorithm
C Program To Find GCD using Pointers and Functions

Video Tutorial: C Program To Find GCD using Repeated Subtraction


[youtube https://www.youtube.com/watch?v=sv8Jehsydrs]

YouTube Link: https://www.youtube.com/watch?v=sv8Jehsydrs [Watch the Video In Full Screen.]


Source Code: C Program To Find GCD using Repeated Subtraction

#include<stdio.h>

int main()
{
    int num1, num2;

    printf("Enter 2 positive integer numbers\n");
    scanf("%d%d", &num1, &num2);

    num1 = (num1 < 0) ? -num1 : num1;
    num2 = (num2 < 0) ? -num2 : num2;

    printf("\nGreatest Common Divisor of %d and %d is ", num1, num2);

    while(num1 != num2)
    {
        if(num1 > num2)
        {
            num1 = num1 - num2;
        }
        else
        {
            num2 = num2 - num1;
        }
    }

    printf("%d.\n", num1);

    return 0;
}

Output 1:
Enter 2 positive integer numbers
20
30

Greatest Common Divisor of 20 and 30 is 10.

Output 2:
Enter 2 positive integer numbers
1980
1617

Greatest Common Divisor of 1980 and 1617 is 33.

Logic To Find GCD using Repeated Subtraction

Lets assume that num1 = 15 and num2 = 20. Lets calculate GCD for these 2 numbers.

While loop iterates until num1 is equal to num2.

num1num2Greater NoSubtract NumbersResult
1520num2 = 20num2 =
num2 – num1
num2:
20 – 15 = 5
155num1 = 15num1 =
num1 – num2
num1:
15- 5 = 10
105num1 = 10num1 =
num1 – num2
num1:
10- 5 = 5
55Both Are Equalnum1 == num2GCD is 5.

You can see below code in the C program i.e., converting a negative number into positive. Our source code above works only for positive integer numbers without this code. If the user enters negative value we use ternary operator to make it a positive value.

    num1 = (num1 < 0) ? -num1 : num1;  
    num2 = (num2 < 0) ? -num2 : num2;  

Here we check if num1 is less than 0. If true, then value of num1 is negative. So we multiply the number by -, which gives us a positive number. For example, if num1 is -15, then -(-15) is +15.

Ternary Operator / Conditional Operator In C

You can make use of simple if else statement like below, to convert negative number into positive:

#include<stdio.h>
if(num1 < 0)
   num1 = num1 * -1;

if(num2 < 0)
   num2 = num2 * -1;

That would convert a negative number to positive number.

While Loop
While loop iterates until num1 is not equal to num2. Once num1 is equal to num2, control exits while loop. Whatever is present in num1 or num2 is the GCD of 2 positive integer numbers entered by the user.

Inside while loop, we check if num1 is greater than num2. If true, we subtract num2 from num1 and store it back inside variable num1. Else if num2 is greater than num1, then we subtract num1 from num2 and store it back inside num2. We repeat this until num1 is equal to num2.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Find GCD using Pointers and Functions

Write a function to compute the greatest common divisor given by Euclid’s algorithm, exemplified for J = 1980, K = 1617 as follows:

1980 / 1617 = 11980 – 1 * 1617 = 363
1617 / 363 = 41617 – 4 * 363 = 165
363 / 165 = 2363 – 2 * 165 = 33
5 / 33 = 5165 – 5 * 33 = 0

Thus, the greatest common divisor is 33.

Analyze Above Problem Statement

1. We need to find Greatest Common Divisor(GCD) of 2 numbers entered by the user, using Euclid’s Algorithm.

2. If J = 1980 and K = 1617, GCD should be 33.

3. Make sure to use the calculation part as shown in problem statement.

4. We observe the calculation part in problem statement and formulate some formulas to figure out the result i.e., GCD of 2 numbers input by the user.

Related Read:
C Program To Find GCD and LCM of Two Numbers using Euclidean algorithm

Video Tutorial: C Program To Find GCD using Pointers and Functions, using Euclid’s Algorithm


[youtube https://www.youtube.com/watch?v=mwDUeKUURbM]

YouTube Link: https://www.youtube.com/watch?v=mwDUeKUURbM [Watch the Video In Full Screen.]


Source Code: C Program To Find GCD using Pointers and Functions, using Euclid’s Algorithm

#include<stdio.h>

void calc_gcd(int, int, int*);

int main()
{
    int j, k, gcd;

    printf("Enter 2 integer numbers\n");
    scanf("%d%d", &j, &k);

    calc_gcd(j, k, &gcd);

    printf("\nGreatest Common Divisor of %d and %d is %d.\n", j, k, gcd);

    return 0;
}

void calc_gcd(int numerator, int denominator, int *gcd)
{
    int temp, num;

    if(denominator == 0)
    {
        *gcd = numerator;
    }
    else if(numerator == 0)
    {
        *gcd = denominator;
    }
    else
    {
        num  = numerator / denominator;
        temp = numerator - num * denominator;

        while(temp)
        {
            numerator   = denominator;
            denominator = temp;
            num  = numerator / denominator;
            temp = numerator - num * denominator;
        }

        *gcd = denominator;
    }
}

Output 1:
Enter 2 integer numbers
1980
1617

Greatest Common Divisor of 1980 and 1617 is 33.

Output 2:
Enter 2 integer numbers
1617
1980

Greatest Common Divisor of 1617 and 1980 is 33.

Output 3:
Enter 2 integer numbers
15
20

Greatest Common Divisor of 15 and 20 is 5.

Output 4:
Enter 2 integer numbers
20
15

Greatest Common Divisor of 20 and 15 is 5.

Logic To Find GCD using Pointers and Functions, using Euclid’s Algorithm

We ask the user to input integer values for variables j and k. We pass values of j and k and address of variable gcd to a function called calc_gcd().

Inside calc_gcd() function
Inside calc_gcd() function we use the following calculations:

Note: We copy the value of j, k and &gcd passed by main method into local variables of calc_gcd() i.e., numerator, denominator and *gcd.

Step 1: We check if denominator is 0. In that case the value present in numerator itself is the GCD. So we copy value present in variable numerator to *gcd.

Step 2: If denominator is not zero. Then, we divide numerator with denominator value and store the result into a variable called num.

num = numerator / denominator;

If j = 1980 and k = 1617, then numerator = 1980 and denominator = 1617.

num = numerator / denominator;
num = 1980/ 1617;
num = 1;

According to problem statement:

1980 / 1617 = 11980 – 1 * 1617 = 363

We’ve formulated the equation for the first part i.e., 1980 / 1617 = 1
Now lets formulate an equation for the second part i.e., 1980 – 1 * 1617 = 363

If you look at 1980 – 1 * 1617 = 363 closely and substitute the values with corresponding variables then you’ll come up with below formula:

temp = numerator – num * denominator;

Look at Step 1 for values of numerator, denominator and num.

Now lets look at the equations given in the problem statement:

1980 / 1617 = 11980 – 1 * 1617 = 363
1617 / 363 = 41617 – 4 * 363 = 165

In this look at 1617 / 363 = 4. Here the value of denominator has been shifted to numerators place, and the value of temp has been copied to denominator. So lets write the code:

numerator = denominator;
denominator = temp;

Step 3: Now lets use these formulate in co-ordination to finish writing our function code.

We need to repeat the code in order to get the results according to the columns present in the problem statement equations:

Here are our formulas:

   
        num         = numerator / denominator;
        temp        = numerator - num * denominator;     
        numerator   = denominator;
        denominator = temp;

Here are the steps in problem statement to calculate the GCD:

1980 / 1617 = 11980 – 1 * 1617 = 363
1617 / 363 = 41617 – 4 * 363 = 165
363 / 165 = 2363 – 2 * 165 = 33
5 / 33 = 5165 – 5 * 33 = 0

We need to repeat execution of our code to get above result:

num  = numerator / denominator;
temp = numerator - num * denominator;

     while(temp)
     {
        numerator   = denominator;
        denominator = temp;
        num  = numerator / denominator;
        temp = numerator - num * denominator;
      }

      *gcd = denominator;

We need to put our code inside a looping construct to repeat the code. Here we are using while loop. So while loop iterates until temp value is positive. Once value of temp is 0, the control exits the while loop.

We have written 2 lines of code before the while loop:

num  = numerator / denominator;
temp = numerator - num * denominator;

that is because we need to have some value inside variable temp before using it as condition for while loop.

Once the value of temp is 0, control exits while loop. Outside while loop we transfer the value present inside denominator to *gcd.

So *gcd will have the Greatest Common Divisor for values input by the user(j = 1980 and k = 1617).

Observe this table from problem statement

1980 / 1617 = 11980 – 1 * 1617 = 363
1617 / 363 = 41617 – 4 * 363 = 165
363 / 165 = 2363 – 2 * 165 = 33
5 / 33 = 5165 – 5 * 33 = 0

When temp value is 0, value of denominator is 33 – which is the Greatest Common Divisor of numbers 1980 and 1617.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Print N Co-Prime Numbers

Lets write a C program to print N co-prime or relative prime numbers. N being the user entered limit for printing the co-prime number pairs.

Co-Prime numbers / Relative Prime Numbers: Two numbers are said to be co-prime or relative prime numbers if they do not have a common factor other than 1.

OR

Two numbers whose Greatest Common Divisor(GCD) is 1 are known as Co-Prime or Relative Prime Numbers.

Note: User entered numbers(to check for co-prime) do not require to be prime numbers.

Related Read:
C Program to Find Factors of a Number using For Loop

Factors of a number: All the numbers which perfectly divide a given number are called as Factors of that number.

Expected Result

If user inputs limit = 5
Output
1. ( 2, 3 ) are co-prime numbers.
2. ( 3, 4 ) are co-prime numbers.
3. ( 2, 5 ) are co-prime numbers.
4. ( 3, 5 ) are co-prime numbers.
5. ( 4, 5 ) are co-prime numbers.

Logic To Find If Two Numbers are Co-Prime or Not

Entire logic is present in our previous video tutorial. Please visit the link and watch the video without fail before going further: C Program To Find Two Numbers are Co-Prime or Not

Video Tutorial: C Program To Print N Co-Prime Numbers


[youtube https://www.youtube.com/watch?v=EnXhsLgFlAQ]

YouTube Link: https://www.youtube.com/watch?v=EnXhsLgFlAQ [Watch the Video In Full Screen.]

Source Code: C Program To Print N Co-Prime Numbers

#include<stdio.h>

int main()
{
    int limit, num1, num2 = 3, count, flag, slno = 1;

    printf("How many co-prime numbers you want to print?\n");
    scanf("%d", &limit);

    while(limit)
    {

        for(num1 = 2; num1 <= num2; num1++)
        {
            for(count = 2; count <= num1; count++)
            {
                flag = 1;
                if(num1 % count == 0 && num2 % count == 0)
                {
                    flag = 0;
                    break;
                }
            }

            if(flag)
            {
                printf("%d. (%d, %d) are co-prime numbers.\n", 
                      slno++, num1, num2);
                limit--;

                if(limit == 0)
                {
                    num1 = num2 + 10;
                }
            }

        }

        num2++;
    }

    return 0;
}

Output 1:
How many co-prime numbers you want to print?
10
1. ( 2, 3 ) are co-prime numbers.
2. ( 3, 4 ) are co-prime numbers.
3. ( 2, 5 ) are co-prime numbers.
4. ( 3, 5 ) are co-prime numbers.
5. ( 4, 5 ) are co-prime numbers.
6. ( 5, 6 ) are co-prime numbers.
7. ( 2, 7 ) are co-prime numbers.
8. ( 3, 7 ) are co-prime numbers.
9. ( 4, 7 ) are co-prime numbers.
10. ( 5, 7 ) are co-prime numbers.

Output 2:
How many co-prime numbers you want to print?
14
1. ( 2, 3 ) are co-prime numbers.
2. ( 3, 4 ) are co-prime numbers.
3. ( 2, 5 ) are co-prime numbers.
4. ( 3, 5 ) are co-prime numbers.
5. ( 4, 5 ) are co-prime numbers.
6. ( 5, 6 ) are co-prime numbers.
7. ( 2, 7 ) are co-prime numbers.
8. ( 3, 7 ) are co-prime numbers.
9. ( 4, 7 ) are co-prime numbers.
10. ( 5, 7 ) are co-prime numbers.
11. ( 6, 7 ) are co-prime numbers.
12. ( 3, 8 ) are co-prime numbers.
13. ( 5, 8 ) are co-prime numbers.
14. ( 7, 8 ) are co-prime numbers.

Logic To Print N Co-Prime Numbers

User enters limit value i.e., how many co-prime numbers he or she wants to print. We put that limit inside while loop condition. So while loop code executes repeatedly until limit is not equal to 0. We decrement the value of limit by 1 as and when we print the co-prime numbers.

Inside while loop we write nested for loop. The outer for loop selects the values for num1 and num2. We know that the first co-prime or relative prime number is 2 and 3. So we initialize num1 = 2 and num2 = 3. We keep incrementing the value of num2 by one outside the outer for loop, and iterate the for loop until num1 is less than or equal to num2.

If num2 is 3, then for loop checks for (num1 always starts from 2, till num1 <= num2) – (2, 2), (3, 2).

Next num2 will be 4. So for loop checks for – (2, 4), (3, 4), (4, 4)

Next num2 will be 5. So for loop checks for – (2, 5), (3, 5), (3, 5), (4, 5) ..and so on.

Inside inner for loop we check if the selected numbers present in num1 and num2 are co-prime or not. That logic is present at C Program To Find Two Numbers are Co-Prime or Not.

Note: Since limit– is inside a for loop, even though limit becomes 0 the while loop won’t exit immediately, until the for loop completes its iterations. It avoid that, we make sure the value of num1 is assigned number greater than num2. That way control exits for loop. Since limit is 0, the control even exits while loop.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Find If Two Numbers are Co-Prime or Not using Function

Lets write a C program to check whether two positive numbers entered by the user are Co-Prime numbers / Relative Prime Numbers or not using function / method.

Co-Prime numbers / Relative Prime Numbers: Two numbers are said to be co-prime or relative prime numbers if they do not have a common factor other than 1.

OR

Two numbers whose Greatest Common Divisor(GCD) is 1 are known as Co-Prime or Relative Prime Numbers.

Factors of a number: All the numbers which perfectly divide a given number are called as Factors of that number.

Note: User entered numbers(to check for co-prime) do not require to be prime numbers.

Logic To Find If Two Numbers are Co-Prime or Not

Complete logic is present in our previous day video tutorial, please watch it before continuing: C Program To Find Two Numbers are Co-Prime or Not

Related Read:
C Program To Find Prime Number or Not using While Loop
C Program to Find Factors of a Number using For Loop
Biggest of Two Numbers Using Ternary Operator: C
C Program to Find GCD or HCF of Two Numbers

Video Tutorial: C Program To Find If Two Numbers are Co-Prime or Not using Function


[youtube https://www.youtube.com/watch?v=e_ZRmnrSVhA]

YouTube Link: https://www.youtube.com/watch?v=e_ZRmnrSVhA [Watch the Video In Full Screen.]

Source Code: C Program To Find If Two Numbers are Co-Prime or Not using Function

#include<stdio.h>

int coprime(int num1, int num2)
{
    int min, count, flag = 1;

    min = num1 < num2 ? num1 : num2;

    for(count = 2; count <= min; count++)
    {
        if( num1 % count == 0 && num2 % count == 0 )
        {
            flag = 0;
            break;
        }
    }

    return(flag);
}

int main()
{
    int n1, n2;

    printf("Enter 2 positive numbers\n");
    scanf("%d%d", &n1, &n2);

    if( coprime(n1, n2) )
    {
        printf("%d and %d are co-prime numbers.\n", n1, n2);
    }
    else
    {
        printf("%d and %d are not co-prime numbers.\n", n1, n2);
    }

    return 0;
}

Output 1:
Enter 2 positive numbers
8
15
8 and 15 are co-prime numbers.

Output 2:
Enter 2 positive numbers
12
15
12 and 15 are not co-prime numbers.

Note:
coprime() method returns 1 or 0 value. If it returns 1, then the code inside if block gets executed. If it returns 0, then the code inside else block gets executed.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert