文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>SPOJ-2-Prime Generator

SPOJ-2-Prime Generator

时间:2011-01-23  来源:vSylar

“收集图案来纪念一下~”

细节很重要的,因为没有考虑完整交了四次才过…

 

for(j=2;j<=e2+1;j++)
        {
            if(is[j]){
                      for(x=a1-a1%j;x<=a2;x+=j)
                      { m=x-a1;
                        if(m>=0&&x!=j) test[m]=0; 
                      }
                     }
        }

 

这里的起点位置还有素数本身的保留都容易忘…用的筛法求素数

 

代码:

 

#include<stdio.h>
#include<string.h>
#include<cmath>
#include<stdlib.h>
//#include <time.h>

#define M 31700
#define N 100005

using namespace std;

bool is[M],test[N];

void getprime(int a,int b)
{ 
     int i,j,k=0;
     int e=(int)(sqrt(0.0+M));
     memset(is,1,sizeof(is));
     is[0]=0;is[1]=0;
     for(i=4;i<b;i+=2) is[i]=0;
     for(i=3;i<e;i+=2)if(is[i])
     {
         for(j=i*i;j<b;j+=2*i)
         is[j]=0;                          
     }
}
int main()
{
  //  clock_t tt=clock();
    int t,a1,a2,j,e2,k,x,e3,m;
    getprime(1,M);
    scanf("%d",&t);
    for(int i=1;i<=t;i++)
    {
        scanf("%d %d",&a1,&a2);
        if(a1==1)a1++;
        k=a2-a1+1;
        memset(test,1,sizeof(test));
        e2=(int)(sqrt(0.0+a2)+1);
        for(j=2;j<=e2+1;j++)
        {
            if(is[j]){
                      for(x=a1-a1%j;x<=a2;x+=j)
                      { m=x-a1;
                        if(m>=0&&x!=j) test[m]=0; 
                      }
                     }
        }
        for(j=0;j<k;j++) if(test[j]) printf("%d\n",j+a1);
  //    for(j=1;j<=1000;j++)if(is[j]) printf("%d ",j);
      printf("\n");    
    }
  //  printf("Time:%f\n",1.0*(clock()-tt)/CLOCKS_PER_SEC);
  // system("pause");
    return 0;
}

原题见:https://www.spoj.pl/problems/PRIME1/

摘录:

2. Prime Generator

Problem code: PRIME1

 

Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!

Input

The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.

Output

For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.

Example

Input:
2
1 10
3 5

Output:
2
3
5
7

3
5

Warning: large Input/Output data, be careful with certain languages (though most should be OK if the algorithm is well designed)

Added by: Adam Dzedzej
Date: 2004-05-01
Time limit: 6s
Source limit: 50000B
Languages: All except: PERL 6

 

相关阅读 更多 +
排行榜 更多 +
别惹神枪手安卓版

别惹神枪手安卓版

冒险解谜 下载
坦克战争世界

坦克战争世界

模拟经营 下载
丛林反击战

丛林反击战

飞行射击 下载