方法一:更相减损法
用两数中较大数减去较小数求得余数,再将余数和减数相比较较大的一个赋给减数成为被减数,较小的一个赋给余数成为减数,
再用前面的方法进行处理直至余数为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;
}