欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

练习题007:求两个数的最大公因数和最小公倍数

程序员文章站 2022-05-11 20:25:00
...

C语言练习题目录索引

最大公约数:辗转相除法;
最小公倍数=两数之积 / 两者的最大公约数。

#include <stdio.h>
#include <windows.h>

int main()
{
    unsigned long number1 = 0;  //两个整数
    unsigned long number2 = 0;
    unsigned long tem = 0;

    unsigned long gcd = 0; //最大公约数
    unsigned long lcm = 0; //最小公倍数

    while (1)
    {
        printf("Please input two numbers: ");
        scanf("%lu%lu", &number1, &number2);

        if (number1 <= 0 || number2 <= 0) 
        {
            printf("input error!\n");
            continue;
        }
        else
        {
            break;
        }
    }

    unsigned long r1 = number1; //保留两个整数的初始值,方便以后计算最大公倍数
    unsigned long r2 = number2;

    while (number1 % number2 != 0)
    {
        tem = number1 % number2;
        number1 = number2;
        number2 = tem;
    }

    gcd = number2;
    lcm = (r1 * r2) / gcd;
    printf("Their Greatest Common Divisor is %lu.\n", gcd);
    printf("Their Least Common Multiple is %lu.\n", lcm);

    system("pause");
    return 0;
}

运行结果:
练习题007:求两个数的最大公因数和最小公倍数