起源

辗转相除法, 又名欧几里德算法(Euclidean algorithm)乃求两个正整数之最大公因子的算法。

算法示意图

图片描述

递归法

int getGcd(int a, int b) {
    return b == 0 ? a : getGcd(b, a % b);
}

示例代码

#include <stdio.h>
#include <math.h>

int getGcd(int a, int b) {
    return b == 0 ? a : getGcd(b, a % b);
}

int main() {
    int a, b;
    while (scanf("%d%d", &a, &b) != EOF) {
        printf("%d\n", getGcd(a, b));
    }
}

KoreyLee
27 声望6 粉丝

Those who were seen dancing were thought to be insane by those who could not hear the music.


引用和评论

0 条评论