最大公约数和最小公倍数

来源:互联网 发布:2kol怎么显示数据 编辑:程序博客网 时间:2024/06/06 16:59

求任意两个正整数的最大公约数和最小公倍数

求公约数:总是将大数除以较小数,留下余数,代替原有大数。if a>b {a=a%b else b=b%a}
     重复这一过程
     直到余数=0,则另一数即为公约数
公倍数=两数相乘 除以公约数。
 1 #include <stdio.h>
  2 
  3 int main()
  4 {
  5     int a, b, num1, num2, temp;
  6     printf("Input a&b:");
  7     scanf("%d%d", &num1, &num2);
  8     if (num1 > num2)
  9     {
 10         temp=num1;
 11         num1=num2;
 12         num2=temp;
 13     }
 14     a=num1;
 15     b=num2;
 16     while (b!=0)
 17     {
 18         temp=a%b;
 19         a=b;
 20         b=temp;
 21     }
 22     printf("The GCD of %d and %d is: %d\n", num1, num2, a);
 23     printf("THe LCM of them is:%d\n",num1*num2/a);
 24     return 0;
 25 }

[root@localhost 42]# vim GCDLCM.c 
[root@localhost 42]# gcc GCDLCM.c 
[root@localhost 42]# ./a.out 
Input a&b:20 55
The GCD of 20 and 55 is: 5
THe LCM of them is:220

0 0
原创粉丝点击