1. 用更相减损法求最大公约数,所谓更相减损法,即“以少减多,更相减损,求其等也,以等数约之,等数约之,即除也,其所以相减者皆等数之重叠,故以等数约之”。
// Calculate the Greatest Common Divisor (GCD) of two numbers
int gcd(int a, int b)
{
while (b != a)
{
if (a > b)
a = a - b;
if (a < b)
b = b - a;
}
return a;//or return b since a and b are equal at this moment.
}
#include<stdio.h>
int main()
{
int x, y, z;
printf("Please input two integers:\n");
scanf("%d %d",&x,&y);
z = gcd(x, y);
printf("The GCD of these two numbers are %d\n",z);
return 0;
}
or:
// Calculate the Greatest Common Divisor (GCD) of two numbers
int gcd(int a, int b)
{
if(a < b)
return gcd(b, a);
if(b == 0)
return a;
else
return gcd(a-b, b);
}
#include<stdio.h>
int main()
{
int x, y, z;
printf("Please input two integers:\n");
scanf("%d %d",&x,&y);
z = gcd(x, y);
printf("The GCD of these two numbers are %d\n",z);
return 0;
}
Input: Please input two integers:
6 9
Output:
The GCD of these two numbers are 3
2. 用辗转相除法求最大公约数,所谓辗转相除法,即 “两个整数的最大公约数等于其中较小的数和两数的相除余数的最大公约数”.
int GCD(int m, int n)
{
int t,r;
if (m < n)
{
t = m;
m = n;
n = t;
}
r = m % n;
if (r == 0)
return n;
else
return GCD(r,n);
}
#include<stdio.h>
int main()
{
int x, y, res;
printf("Please input two numbers:\n");
scanf("%d %d", &x, &y);
res = GCD(x, y);
printf("The GCD of %d and %d is %d\n", x, y, res);
return 0;
}
or:
int GCD(int m, int n)
{
int t;
if (m < n)
{
t = m;
m = n;
n = t;
}
return (!n)?m:GCD(n,m%n);
}
#include<stdio.h>
int main()
{
int x, y, res;
printf("Please input two numbers:\n");
scanf("%d %d", &x, &y);
res = GCD(x, y);
printf("The GCD of %d and %d is %d\n", x, y, res);
return 0;
}
Input:
Please input two integers:6 9
Output:
The GCD of these two numbers are 3
3. 两个数的 最小公倍数等于两个数的乘积除以最大公约数。
// Calculate the Lowest Common Multiple (LCP) of two intergers
int gcd(int a, int b)
{
while (b != a)
{
if (a > b)
a = a - b;
if (a < b)
b = b - a;
}
return a;
}
#include<stdio.h>
int main()
{
int x, y, z;
printf("Please input two integers:\n");
scanf("%d %d",&x,&y);
z = (x * y) / gcd(x, y);
printf("The LCP of these two intergers is %d\n",z);
return 0;
}
Input:
Please input two integers:6 9
Output:
The LCP of these two numbers are 18