Cover Image for GCD of two numbers in C
50 views

GCD of two numbers in C

To find the greatest common divisor (GCD) of two numbers in C, you can use the Euclidean algorithm, which is an efficient method for calculating the GCD of two integers. Here’s a C program to calculate the GCD of two numbers:

C
#include <stdio.h>

// Function to calculate the GCD using the Euclidean algorithm
int gcd(int a, int b) {
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

int main() {
    int num1, num2;

    printf("Enter two numbers: ");
    scanf("%d %d", &num1, &num2);

    // Ensure both numbers are positive
    if (num1 < 0) num1 = -num1;
    if (num2 < 0) num2 = -num2;

    int result = gcd(num1, num2);

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

    return 0;
}

In this program:

  1. We define a gcd function that calculates the GCD using the Euclidean algorithm. The algorithm repeatedly replaces the larger number with the remainder of the division of the larger number by the smaller number until the smaller number becomes zero. The GCD is the value of the remaining larger number.
  2. In the main function, we input two numbers from the user.
  3. To ensure that negative numbers don’t affect the GCD calculation, we take the absolute values of the input numbers using if statements.
  4. We call the gcd function with the absolute values of the input numbers and store the result.
  5. Finally, we print the GCD of the two input numbers.

Compile and run the program, and it will calculate and display the GCD of the two numbers you provide as input.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS