输入两个正整数m和n,求其最大公约数和最小公倍数。

 #include
#define STRAS "*****************************"
int gcd(int a, int b);  //最大公约数
int lcm(int a, int b);  //最小公倍数
int main(void)
{
    int n, m;
    int result_gcd, result_lcm;
    printf("Enter two integers.Please:(q to quit)");
    while(scanf("%d%d",&n,&m) == 2)
    {
        result_gcd = gcd(n,m);
        result_lcm = lcm(n,m);
        printf("\n%s\n\n",STRAS);
        printf("greatest common divisor:   %d\n",result_gcd);
        printf("least common multiple:     %d\n",result_lcm);
        printf("\n%s\n",STRAS);
        printf("Enter two  integers again,please:(q to quit)");
    }
    printf("Thank you for your use! goodbye!!\n");
    getchar();
    return 0;
}
//int gcd(int a,int b)
//{
//    return b == 0 ? a : gcd(b,a%b);
//
//}


int gcd(int a, int b)
{
    int temp;
    if(a > b)    //如果第一位数大于第二位,这里需要交换一下位置
    {
        temp = a;
        a = b;
        b = temp;
    }
    while(b != 0) //注意,这里的b已经是a的值
    {             //用辗转相除法,求出最大公约数
        temp = a % b;
        a = b;
        b = temp;
    }
    return a;    //当辗转相除b=0后,说明此时的a就是最大公约数
}
int lcm(int a, int b)
{
    int temp;    //最小公倍数 等于 两数之积 除 最大公约数
    temp = a*b / gcd(a,b);
    return temp;
}

 

你可能感兴趣的:(C语言)