数论模板

判断两数是否互质:

#include<iostream>  
using namespace std;  
  
bool isCoprime(int x,int y)  
{  
    if(x==1 && y==1)//1和1互质  
        return true;  
    else if(x<=0 || y<=0 || x==y)//非正整数都不存在互质的说法  
        return false;  
    else if(x==1 || y==1)//1和任何正整数都互质  
        return true;  
    else  
    {  
        int tmp=0;  
        //使用求商判断法,如果输入的x<y,第一次循环会交换x和y的位置  
        while(true)  
        {  
            tmp=x%y;  
            if(tmp==0)  
            {  
                break;  
            }  
            else  
            {  
                x=y;  
                y=tmp;  
            }  
        }  
        if(y==1)          //最大公约数为1,所以互质  
            return true;  
        else              //最大公约数大于1,所以不互质  
            return false;  
  
    }  
}  
  
int main(void)  
{  
    bool ret=isCoprime(19,6);  
  
    cout<<ret<<endl;  
    return 0;  
}  

猜你喜欢

转载自blog.csdn.net/FZdeAmbition/article/details/80056694