最大公约数与最小公倍数

辗转相除法求最大公约数

举例:24,18,最大公约数为6
24 / 18 = 1 ... 6
18 / 6 = 3 ... 0
当余数为0时,除数即为最大公约数

两数之积除最大公约数即为最小公倍数

实现代码如下

#include <stdio.h>
#include <stdlib.h>

int main(){
    int a, b;
    //最大公约数
    scanf("%d%d", &a, &b);
    if(b > a){  //确保a>b
        int t = a;
        a = b;
        b = a;
    }
    int c = a % b;	//c为余数
    while(c){
        a = b;
        b = c;
        c = a % b;
    }
    printf("result = %d\n", b);
    return 0;
}
posted @ 2023-01-28 16:57  dctwan  阅读(11)  评论(0编辑  收藏  举报