How to find the greatest common divisor (c++)
When seeking the maximum convention, there are many code implementations, such as the rolling and dividing method. In addition, a better understanding method is recommended here.
The following is the code implementation:
#include<iostream>
using namespace std;
int gcd(int a,int b)
{
if(b==0)
{
return a;
}
else
{
return gcd(b,a%b);
}
}
int main()
{
int m,n;
cin>>n>>m;
cout<<gcd(n,m);//在devc++中有__gcd()函数可以直接调用,但是VS中没有,具体原因可以试着查查
return 0;
}
/*
devc++中可以直接写成
#include<iostream>
using namespace std;
int main()
{
int n,m;
cin>>n>>m;
cout<<__gcd(n,m)<<endl;
return 0;
}
//你说代码简单不简单
*/
After reading the above, I don’t understand, but it doesn’t matter, there are more specifics below:
#include<iostream>
using namespace std;
int main()
{
int n,m;
cin>>n>>m;
while(n!=m)
{
if(m>n)
{
m=m-n;
}
else
{
n=n-m;
}
}
cout<<n<<endl;//最后得到的n、m是相等的,所以输出n、m都无所谓
return 0;
}
If you still want to find the greatest common multiple, it is even simpler. In fact, it is: first find the greatest common divisor of m and n, and then divide by the product of two; refer to the previous code;
Code:
#include<iostream>
using namespace std;
int main()
{
int n,m,a,b;
cin>>n>>m;
a=n,b=m;//对原来的值进行保留
while(n!=m)
{
if(m>n)
{
m=m-n;
}
else
{
n=n-m;
}
}
//重点是下行代码
cout<<a*b/n<<endl;//为了避免数据溢出可以写成a/n*b
return 0;
}
It is the first time to write CDSN, and some things are not done well.