c语言求最大公约数和最小公倍数

方法一:更相减损法

用两数中较大数减去较小数求得余数,再将余数和减数相比较较大的一个赋给减数成为被减数,较小的一个赋给余数成为减数,

再用前面的方法进行处理直至余数为0,此时的被减数就是这两个数的最大公约数.两数乘积再除以最大公约数即可得到最小公倍数。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<assert.h>
#pragma warning(disable: 4996)

void swap(int *x, int *y)
{
*x ^= *y;
*y ^= *x;
*x ^= *y;
}


int main()
{
int num1 = 12;
int m = num1;
int num2 = 18;
int n = num2;
int product = m*n;
int r = 1;
while (0!=r)
{
if (num1 < num2)
{
swap(&num1, &num2);
}
r = num1 - num2;
if (r > num2)
{
swap(&r, &num2);
}
num1 = num2;
num2 = r;
}
int minmul = product / num1;
printf("the greatest common divisor of %d and %d is: %d\n", m, n, num1);
printf("the  least common multiple of %d and %d is: %d\n",m,n,minmul);
system("pause");
return 0;
}



方法二:辗转相除法


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<assert.h>
#pragma warning(disable: 4996)

void swap(int *x, int *y)
{
*x ^= *y;
*y ^= *x;
*x ^= *y;
}

int main()
{
int num1 = 12;
int m = num1;
int num2 = 18;
int n = num2;
int product = num1*num2;
int quotient = 0;
int r = 1;
while (r != 0)
{
if (num1 < num2)
{
swap(&num1, &num2);
}
quotient = num1 / num2;
r = num1%num2;
num1 = num2;
num2 = r;
}
int minmul = product / num1;
printf("the greatest common divisor of %d and %d is: %d\n", m, n, num1);
printf("the  least common multiple of %d and %d is: %d\n", m, n, minmul);
system("pause");
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值