C++求两个整数的最大公约数和最小公倍数

时间:2015-05-15 01:18:58   收藏:0   阅读:150

最小公倍数=两个整数的成绩 / 最大公约数

求最大公约数的方法:

(1)辗转相除法

 1 #include <iostream>
 2 using namespace std;
 3 int main()
 4 {
 5     int a,b,tmp,m;
 6     cin>>a>>b;
 7     m=a*b;
 8     if(a<b)
 9     {
10         tmp=b;
11         b=a;
12         a=tmp;
13     }
14     while(b!=0)
15     {
16         tmp=a%b;
17         a=b;
18         b=tmp;
19     }
20     cout<<"LCD:"<<a<<endl;
21     cout<<"LCM:"<<m/a<<endl;
22 }

(2)相减法

 1 #include <iostream>
 2 using namespace std;
 3 int main()
 4 {
 5     int a,b,tmp,m;
 6     cin>>a>>b;
 7     m=a*b;
 8     while(a!=b)
 9     {
10         if(a>b) a=a-b;
11         else b=b-a;
12     }
13     cout<<"LCD:"<<a<<endl;
14     cout<<"LCM:"<<m/a<<endl;
15 }
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!