首页 > 其他分享 >最大公约数 GCD greatest common divisor

最大公约数 GCD greatest common divisor

时间:2022-12-14 20:47:07浏览次数:62  
标签:divisor GCD int gcd b1 b2 common

 

辗转相除法

#include <stdio.h>

int main(void) {
    int m, n, r;
    scanf("%d%d", &m, &n);
    if (m < n) {
        m = m ^ n;
        n = m ^ n;
        m = m ^ n;
    }
    while (n) {
        r = m % n;
        m = n;
        n = r;
    }
    printf("great common divisor %d\n", m);
    return 0;
}

 

更相减损法

def gcd(b1: int, b2: int) -> int:
    if b1 < b2:
        b1, b2 = b2, b1
    while b1 - b2 != b2:
        t = b1 - b2
        b1, b2 = (b2, t) if b2 > t else (t, b2)
    return b2


print(gcd(182, 98))
print(gcd(63, 98))

 

标签:divisor,GCD,int,gcd,b1,b2,common
From: https://www.cnblogs.com/dissipate/p/16983451.html

相关文章