快速求解gcd和lcm——非递归的欧几里得算法

 1 #include<iostream>
 2 #include<cstdio>
 3 using namespace std;
 4 int n,m;
 5 //求解n,m的gcd和lcm
 6 
 7 int gcd(int a,int b)
 8 {
 9     while(1)
10     {   
11           if(a<b)  {int t=a;a=b;b=t;}
12           if(b==0)  return a;
13           int x=a%b;a=b;b=x;
14     }
15 }
16 
17 int lcm(int a,int b)
18 {
19     return a/gcd(a,b)*b;
20 }
21 
22 int main()
23 {
24     scanf("%d %d",&n,&m);
25     cout<<gcd(n,m)<<endl;
26     cout<<lcm(n,m);
27     return 0;
28 }            

希望自己下次不要再忘记算法啦~~~

猜你喜欢

转载自www.cnblogs.com/mm-puppy-lyt/p/13155687.html
今日推荐