最大公约数的算法竟然如此简单,不说了,见代码
#include <stdio.h>
int gcd(int a, int b)
{
if(b== 0)
return a;
return gcd(b, a%b);
}
简化后如下:
int gcd(int a, int b)
{
return (b==0 ? a: gcd(b, a%b));
}
而最小公倍数的也就为:
int lcm(int a, int b)
{
return (gcd(a, b) == 0 ? 0: a*b/ gcd(a, b));
}
int main()
{
printf("Please input for 2 numbers for gcd. ");
int a, b;
scanf("%d", &a);
scanf("%d", &b);
printf("gcd = %d ", gcd(a, b));
printf("lcm = %d ", lcm(a, b));
return 0;
}