Problem Description
The Children’s Day has passed for some days .Has you remembered something happened at your childhood? I remembered I often played a game called hide handkerchief with my friends.
Now I introduce the game to you. Suppose there are N people played the game ,who sit on the ground forming a circle ,everyone owns a box behind them .Also there is a beautiful handkerchief hid in a box which is one of the boxes .
Then Haha(a friend of mine) is called to find the handkerchief. But he has a strange habit. Each time he will search the next box which is separated by M-1 boxes from the current box. For example, there are three boxes named A,B,C, and now Haha is at place of A. now he decide the M if equal to 2, so he will search A first, then he will search the C box, for C is separated by 2-1 = 1 box B from the current box A . Then he will search the box B ,then he will search the box A.
So after three times he establishes that he can find the beautiful handkerchief. Now I will give you N and M, can you tell me that Haha is able to find the handkerchief or not. If he can, you should tell me "YES", else tell me "POOR Haha".
Input
There will be several test cases; each case input contains two integers N and M, which satisfy the relationship: 1<=M<=100000000 and 3<=N<=100000000. When N=-1 and M=-1 means the end of input case, and you should not process the data.
Output
For each input case, you should only the result that Haha can find the handkerchief or not.
Sample Input
3 2 -1 -1
Sample Output
YES
代码:
#include <stdio.h>
#include<math.h>
//含有公因子 YES(除M=1和M=N),注意N=2时的特殊情况
//N是素数 YES
//注意N可能比M小
/*
判断是否含有公因子
*/
int max,min;
int haveCommonFactor(int N, int M)
{
max=M>N?M:N;
min=M<N?M:N;
int tmp;
while(1)
{
tmp=min;
min=max%min;
if(min==0)
{
return 1;
}
else if(min==1)
{
return 0;
}
max=tmp;
}
return 0;
}
/*
判断是否为素数
因为数据很大,所以采用此种方法,不然超时
*/
int IsPrimeNumber(int num)
{
int tmp;
if(num==2||num==3)
{
return 1;
}
if(num%6!=1&&num%6!=5)
{
return 0;
}
tmp=(int)(sqrt(num));
for(int i=5;i<=tmp+1;i++)
{
if(num%i==0||num%(i+2)==0)
{
return 0;
}
}
return 1;
}
int main()
{
int N, M;
while (1)
{
scanf("%d %d",&N,&M);
if (N==-1&&M==-1)
{
break;
}
//只要M和N有一个为1,就YES
else if(N==1||M==1)
{
printf("YES\n");
continue;
}
//将此判断是否含有公因子放在判断是否为素数之前,就是为了处理N==2这种特殊情况
//如果含有公因子,则 POOR Haha
else if(haveCommonFactor(N,M))
{
printf("POOR Haha\n");
continue;
}
//如果N为素数,则当M==N时,POOR Haha,否则 YES
else if(IsPrimeNumber(N))
{
if(M==N)
{
printf("POOR Haha\n");
continue;
}
else
{
printf("YES\n");
continue;
}
}
//其余情况 YES
else
{
printf("YES\n");
continue;
}
}
return 0;
}