求最大公约数和最小公倍数

来源:互联网 发布:凡人修真2源码 编辑:程序博客网 时间:2024/04/30 04:38


int a = 0, b = 0;

    printf("请输入两个数:");
    scanf("%d%d", &a, &b);
    int max = a > b ? a : b;
    int min = a < b ? a : b;
    //求最大公约数
    for (int i = min; i >= 1; i--) {
        if (a % i == 0 && b % i == 0) {
            printf("最大公约数为:%d\n", i);
            break;
        }
    }
    //求最小公倍数
    for (int i = max; i <= a * b; i++) {
        if (i % a == 0 && i % b == 0) {
            printf("最大公约数为:%d\n", i);
            break;
        }
    }
    
    //辗转相除法(求最大公约数)
    int tempA = a;
    int tempB = b;
    int temp = tempA % tempB;
    while (temp) {
        tempA = tempB;
        tempB = temp;
        temp = tempA % tempB;
    }
    printf("最大公约数为:%d\n", tempB);
    printf("最小公倍数为:%d\n", a * b / tempB);


0 0
原创粉丝点击