我们上小学的时候,我们都学习过求两个数的最大公约数,最小公倍数。求最大公约数的思想是,找出两个书中的最小数,然后用两个数对其求余,如果两个数求余的结果为零,则此时最大公约数。否则将其最小数减一,进行循环判断。求最小公倍数时,现找出两个数中的最大数,然后进行加一操作,求余。当两个数求余都为0即可求出最小公倍数。代码如下:
- #include <stdio.h>
-
-
int gcd(int a, int b)
-
{
-
int min;
-
if(a <= 0 || b <= 0) return -1;
-
if(a > b) min = b;
-
else min = a;
-
-
while(min)
-
{
-
if (a % min == 0 && b % min == 0)
-
return min;
-
min--;
-
}
-
return -1;
-
}
-
-
int lcm(int a, int b)
-
{
-
int max;
-
if(a <= 0 || b <= 0)
-
return -1;
-
-
if(a > b)
-
max = a;
-
else
-
max = b;
-
-
while(max)
-
{
-
if(max % a == 0 && max % b == 0)
-
return max;
-
-
max++;
-
}
-
-
return -1;
-
}
-
-
int main(int argc, char *argv[])
-
{
-
int a,b;
-
printf("please input two digit for getting GCD and LCM\n");
-
scanf("%d %d",&a,&b);
-
printf("the GCD of %d and %d is %d\n",a,b,gcd(a,b));
-
printf("the LCM of %d and %d is %d\n",a,b,lcm(a,b));
-
return 0;
-
}
peng@ubuntu:~$ ./a.out
please input two digit for getting GCD and LCM
4 10
the GCD of 4 and 10 is 2
the LCM of 4 and 10 is 20
阅读(1867) | 评论(0) | 转发(0) |