Number Theory Template

Determine if two numbers are coprime:

#include<iostream>  
using namespace std;  
  
bool isCoprime(int x,int y)  
{  
    if(x==1 && y==1)//1 and 1 are relatively prime  
        return true;  
    else if(x<=0 || y<=0 || x==y)//Non-positive integers have no co-prime statement  
        return false;  
    else if(x==1 || y==1)//1 and any positive integer are coprime  
        return true;  
    else  
    {  
        int tmp=0;  
        //Use the quotient judgment method, if the input x<y, the first cycle will exchange the positions of x and y  
        while(true)  
        {  
            tmp=x%y;  
            if(tmp==0)  
            {  
                break;  
            }  
            else  
            {  
                x=y;  
                y=tmp;  
            }  
        }  
        if(y==1) //The greatest common divisor is 1, so coprime  
            return true;  
        else //The greatest common divisor is greater than 1, so it is not coprime  
            return false;  
  
    }  
}  
  
int main(void)  
{  
    bool ret=isCoprime(19,6);  
  
    cout<<ret<<endl;  
    return 0;  
}  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324723593&siteId=291194637