How to calculate the greatest common divisor of two positive integers in the C language?

#include <stdio.h>

// 计算两个正整数的最大公约数
int gcd(int a, int b) {
    if (b == 0) {
        return a;
    } else {
        return gcd(b, a % b);
    }
}

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

This code uses recursion to calculate the greatest common divisor of two positive integers and outputs the result.

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds