方法一:迭代法
代码:
#include<iostream>
using namespace std;
int main()
{
int GCD(int m,int n);
int m,n,g;
cout<<"输入两个整数m和n(m>n)"<<endl;
cout<<"m:";
cin>>m;
cout<<"n:";
cin>>n;
g=GCD(m,n);
cout<<"m和n的最小公倍数是:";
cout<<g;
system("pause");
}
int GCD(int m,int n)
{
while(m%n!=0)
{
int t=m%n;
m=n;
n=t;
}
return n;
}
方法二:递归法
代码:
#include<iostream>
using namespace std;
int main()
{
int GCD(int m,int n);
int m,n,g;
cout<<"输入两个整数m和n(m>n)"<<endl;
cout<<"m:";
cin>>m;
cout<<"n:";
cin>>n;
g=GCD(m,n);
cout<<"m和n的最小公倍数是:";
cout<<g;
system("pause");
}
int GCD(int m,int n)
{
if(m%n==0)
return n;
else
return GCD(n,m%n);
}
方法三:用栈实现
#include<iostream>
#include<stack>
using namespace std;
int main()
{
int GCD(int m,int n);
int m,n,g;
cout<<"输入两个整数m和n(m>n)"<<endl;
cout<<"m:";
cin>>m;
cout<<"n:";
cin>>n;
g=GCD(m,n);
cout<<"m和n的最小公倍数是:";
cout<<g;
system("pause");
}
int GCD(int m,int n)
{
stack<int> s;
s.push(n);
while(m%n!=0)
{
int t=m%n;
m=n;
n=t;
s.push(n);
}
return s.top();
}
说明:这些代码都是自己写的,难免会不足,多多指教。
int m,n,g;
cout<<"输入两个整数m和n(m>n)"<<endl;
cout<<"m:";
cin>>m;
cout<<"n:";
cin>>n;
g=GCD(m,n);
cout<<"m和n的最小公倍数是:";
cout<<g;
system("pause");
}
int GCD(int m,int n)
{
while(m%n!=0)
{
int t=m%n;
m=n;
n=t;
}
return n;
}
方法二:递归法
代码:
#include<iostream>
using namespace std;
int main()
{
int GCD(int m,int n);
int m,n,g;
cout<<"输入两个整数m和n(m>n)"<<endl;
cout<<"m:";
cin>>m;
cout<<"n:";
cin>>n;
g=GCD(m,n);
cout<<"m和n的最小公倍数是:";
cout<<g;
system("pause");
}
int GCD(int m,int n)
{
if(m%n==0)
return n;
else
return GCD(n,m%n);
}
方法三:用栈实现
#include<iostream>
#include<stack>
using namespace std;
int main()
{
int GCD(int m,int n);
int m,n,g;
cout<<"输入两个整数m和n(m>n)"<<endl;
cout<<"m:";
cin>>m;
cout<<"n:";
cin>>n;
g=GCD(m,n);
cout<<"m和n的最小公倍数是:";
cout<<g;
system("pause");
}
int GCD(int m,int n)
{
stack<int> s;
s.push(n);
while(m%n!=0)
{
int t=m%n;
m=n;
n=t;
s.push(n);
}
return s.top();
}
说明:这些代码都是自己写的,难免会不足,多多指教。
转载于:https://blog.51cto.com/sincerecorner/685771