![JyxSystem专属标志](https://img-blog.csdnimg.cn/20200101125111892.jpg)
纲目:
判断两数是否互质:
程序描述:判断两数是否互质。
思维:欧几里得辗转相除法 求最大公倍数法
Dev C++代码如下:
#include <bits/stdc++.h>
using namespace std;
bool iscop(int x,int y)
{
if(x < y)
{
int t = x;
x = y;
y = t;
}//确保x是大数,便于我们模拟辗转相除法(求余数)
while(true)
{
m = x % y;//求余
if(m == 1)
{
return true;
}
if(m == 0)
{
return false;
}//判断余数(等于0为合数,等于1为质数,大于1为还没辗转尽)
int t = m;
x = y;
y = t;//辗转相除之后原大数没有用,有用的只是原小数与余数,这里的作用是迭换,节省空间
}//模拟辗转相除的过程并求出除到最后的余数
}
int main()
{
int a(0),b(0);
cin>>a>>b;
cout<<iscop(a,b);
return 0;
}
推广部分:
求最大公约数:
原核心部分:
bool iscop(int x,int y)
{
if(x < y)
{
int t = x;
x = y;
y = t;
}//确保x是大数,便于我们模拟辗转相除法(求余数)
while(true)
{
m = x % y;//求余
if(m == 1)
{
return true;
}
if(m == 0)
{
return false;
}//判断余数(等于0为合数,等于1为质数,大于1为还没辗转尽)
int t = m;
x = y;
y = t;//辗转相除之后原大数没有用,有用的只是原小数与余数,这里的作用是迭换,节省空间
}//模拟辗转相除的过程并求出除到最后的余数
}
现核心部分:
int gcd(int x,int y)
{
if(x < y)
{
int t = x;
x = y;
y = t;
}//确保x是大数,便于我们模拟辗转相除法(求余数)
while(true)
{
m = x % y;//求余
if(m == 1)
{
return 1;
}
if(m == 0)
{
return y;
}//m==0成立时
int t = m;
x = y;
y = t;//辗转相除之后原大数没有用,有用的只是原小数与余数,这里的作用是迭换,节省空间
}//模拟辗转相除的过程并求出除到最后的余数
}
判断质数并求出最大公约数可以合并一下,效果如下:
#include <bits/stdc++.h>
using namespace std;
int m(0);
int gcd(int x,int y)
{
if(x < y)
{
int t = x;
x = y;
y = t;
}
while(true)
{
m = x % y;
if(m == 1)
{
return 1;
}
if(m == 0)
{
return y;
}
int t = m;
x = y;
y = t;
}
}
int main()
{
int a(0),b(0);
cin>>a>>b;
int t = gcd(a,b);
if(t == 1)
{
cout<<"互质"<<endl;
cout<<"最大公约数为1"<<endl;
}
else
{
cout<<"不互质"<<endl;
cout<<"最大公约数为"<<t<<endl;
}
return 0;
}