joj 1928

筛选法求素数~~~~~

 

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
using namespace std;
int prim[50000];
int main()
{
    memset(prim,0,sizeof(prim));
    int i;
    for(i=2;i<50000;i++)
    {
       if(prim[i]==0)
       {
          int j;
          for(j=i+i;j<50000;j+=i)
          {
              prim[j]=1;
          }
       }
    }
    int x1,x2;
    while(scanf("%d%d",&x1,&x2)!=EOF)
    {
       if(x1<2)
       {
          x1=2;
       }
       int number[x2-x1+10];
       memset(number,0,sizeof(number));
       int i;
       for(i=2;i<sqrt(x2)+1;i++)
       {
          if(prim[i]==0)
          {
             int j;
             if((x1/i)*i==x1)
             {
                j=0;
             }
             else
             {
                j=(x1/i)*i+i-x1;
             }
             if(j+x1==i)
             {
                j+=i;
             }
             for(;j<=x2-x1;j+=i)
             {
                number[j]=1;
             }
          }
       }
       int j;
       j=0;
       int r,l;
       int now,max=0,min=10000000;
       while(number[j]!=0)
       {
          j++;
       }
       int b1=-1,b2=-1,c1=-1,c2=-1;
       now=j;
       j++;
       for(;j<=x2-x1;j++)
       {
          if(number[j]==0)
          {
             if(j-now>max)
             {
                max=j-now;
                b1=now+x1;
                b2=j+x1;
             }
             if(j-now<min)
             {
                min=j-now;
                c1=now+x1;
                c2=j+x1;
             }
             now=j;
          }
       }
       if(b1==-1)
       {
          printf("There are no adjacent primes.\n");
       }
       else
       {
          printf("%d,%d are closest, %d,%d are most distant.\n",c1,c2,b1,b2);
       }
    }
}

你可能感兴趣的:(joj 1928)