C

C Program To Calculate The GCD Of

This tutorial will teach you how to write a C program to find the GCD of two numbers.

What exactly is GCD?

GCD is an abbreviation for “greatest common divisor.” The GCD of two integer numbers is the largest integer that can divide both numbers exactly, which means the remainder is zero. It is also known as HCF (highest common factor).
As an example: The GCD of 15 and 50 is 5 because it is the largest integer number that can divide both numbers exactly.

Exemplification 1: Using a for loop and an if statement, calculate the GCD of two numbers.

In this example, we are taking user input. The user enters two integer numbers, and the program calculates the GCD of those numbers.
The logic we’re employing here is fairly straightforward. On each iteration, we run a for loop from 1 to the highest number between num1 and num2, and we divide both numbers by the loop counter. Variable gcd stores the I value that divides both numbers without leaving a remainder. The GCD value of these two numbers is the last I value that exactly divides them.

#include <stdio.h>
int main()
{
  int num1, num2, i, gcd;

  printf("Enter two integers: ");
  //Storing user input into num1 and num2
  scanf("%d %d", &num1, &num2);

  for(i=1; i <= num1 && i <= num2; ++i)
  {
    // Checks if the current value of i is
    // factor of both the integers num1 & num2
    if(num1%i==0 && num2%i==0)
      gcd = i;
  }

  printf("GCD of input numbers %d and %d is: %d", num1, num2, gcd);

  return 0;
}

Example 2: Using a while loop to calculate the GCD of two numbers

This is yet another method for calculating the GCD of two numbers. In this method, the smaller of the two integers is subtracted from the larger integer. The result of the subtraction is then assigned to the variable containing the larger integer. This process is repeated in the while loop until both numbers are equal, at which point either of these two variables, num1 and num2, can be printed as output. Both num1 and num2 are equal at the end of the loop and contain the GCD value.

#include <stdio.h>
int main()
{
  int num1, num2;
  printf("Enter two integers: ");
  //Storing user input into num1 and num2
  scanf("%d %d", &num1, &num2);
  while(num1!=num2)
  {
    if(num1 > num2)
      num1 -= num2;
    else
      num2 -= num1;
  }
  printf("GCD of two entered integers is: %d",num1);

  return 0;
}

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button