HDU —2012 素数判定

素数判定

Problem Description
对于表达式n^2+n+41,当n在(x,y)范围内取整数值时(包括x,y)(-39<=x<y<=50),判定该表达式的值是否都为素数。
 


Input
输入数据有多组,每组占一行,由两个整数x,y组成,当x=0,y=0时,表示输入结束,该行不做处理。
 


Output
对于每个给定范围内的取值,如果表达式的值都为素数,则输出"OK",否则请输出“Sorry”,每组输出占一行。


 


Sample Input
0 1
0 0
 


Sample Output
OK

第一次尝试:

#include <stdio.h>
#include <math.h>
int main ()
{
    int x,y;
    while (scanf("%d%d",&x,&y)!=EOF)
    {
        if(x==0&&y==0)break;
        int count=0;
        for(int n=x;n<=y;n++)
        {
            int s;
            s=n*n+n+41;
            for(int i=2;i<sqrt(s);i++)
            {
                if(s%i==0)
                {
                printf("Sorry\n");
                count++;
                break;
                }    
            }        
        }
        if(count==0)printf("OK\n");
    }
    return 0;
}

这里我以为只要找到一个非素数,就会break,break出两个for循环,其实不然,也就是说,他只出了一个循环,n++之后,他还会继续判断是否为素数,这样就可能会多次输出Sorry,因此要加一个步骤,在找到非素数后,应当break出两个for。

第二次尝试:

include <stdio.h>
#include <math.h>
int main ()
{
    int x,y;
    while (scanf("%d%d",&x,&y)!=EOF)
    {
        if(x==0&&y==0)break;
        int count=0;
        for(int n=x;n<=y;n++)
        {
            int s;
            s=n*n+n+41;
            for(int i=2;i<sqrt(s);i++)
            {
                if(s%i==0)
                {
                printf("Sorry\n");
                count++;
                break;
                }
                if(count!=0)break;    
            }        
        }
        if(count==0)printf("OK\n");
    }
    return 0;
}
扫描二维码关注公众号,回复: 2384908 查看本文章

猜你喜欢

转载自blog.csdn.net/floraqiu/article/details/77842121