GCD in C: Loop & Recursion Guide

One can calculate the greatest common divisor in C language using either recursion or loops. Here is an example code using loops:

#include <stdio.h>

int gcd(int a, int b) {
    int temp;
    while (b != 0) {
        temp = a % b;
        a = b;
        b = temp;
    }
    return a;
}

int main() {
    int num1, num2;
    
    printf("请输入两个整数:");
    scanf("%d %d", &num1, &num2);
    
    int result = gcd(num1, num2);
    printf("最大公约数为:%d\n", result);
    
    return 0;
}

In the code above, we have defined a function called “gcd” to calculate the greatest common divisor using the Euclidean algorithm. Then in the main function, we take user input for two integers, call the gcd function to calculate the greatest common divisor, and output the result.

bannerAds