【SPOJ】Prime Generator

SPOJ Problem Set (classical)
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)
———

#include<stdio.h>
#include<math.h>
#define MAX 32000
bool primeTable[MAX]={0};
int smallTable[MAX]={0};

void initPrimeTable(){
    primeTable[0]=1;//not prime
    primeTable[1]=1;
    for(int i=2; i<MAX+1; ++i){
        if(!primeTable[i]){
            for(int j=i*2; j<MAX+1; j=j+i){
                primeTable[j]=1;
            }
        }
    }
}

void makeSmallTable(){
    int j=0;
    for(int i=0; i<MAX; ++i){
        if(!primeTable[i]){
            // printf("%d\n", j);
            smallTable[j++]=i;
        }
    }
}

bool isprime(int num){
    if(num==1)
        return false;
    if(num==2)
        return true;
    if(num<=32000)         
        return !primeTable[num];     
    int sq=sqrt(num)+1;     
    for(int i=0;; i++){         
        int op=smallTable[i];         
        if(op>sq || op==0)
            break;
        if(num%op==0)
            return false;
    }
    return true;
}

int main(){
    initPrimeTable();
    makeSmallTable();
    int a;
    scanf("%d", &a);
    for(int i=0; i<a; i++){
        int low, high;
        scanf("%d%d", &low, &high);
        int b=low;
        if(b==1)
            printf("2\n");
        if(isprime(b))
            printf("%d\n", b);
        if(b%2==0)
            b=b+1;
        else
            b=b+2;
        for(; b<=high; b=b+2){
            if(isprime(b)){
                printf("%d\n", b);
            }
        }
        printf("\n");
    }
    return 0;
}

python太慢过不了,无语

Tags : ,

2 thoughts on “【SPOJ】Prime Generator”

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Click the right image To submit your comment: