我尝试为此[问题]实现分段筛算法:http://www.spoj.pl/problems/PRIME1/,如下所示:
#include <iostream>
#include <string>
#include <set>
#include<math.h>
#include<vector>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cstdio>
#define MAX 32000 // sqrt of the upper range
using namespace std;
int base[MAX]; // 0 indicates prime
vector<int> pv; // vector of primes
int mod (int a, int b)
{
if(b < 0)
return mod(-a, -b);
int ret = a % b;
if(ret < 0)
ret+=b;
return ret;
}
void sieve(){
for(int i = 2 ; i * i < MAX ; i++ )
if(!base[i])
for(int j = i * i ; j < MAX ; j += i )
base[j] = 1;
for(int i = 2 ; i < MAX ; i++ )
if(!base[i]) pv.push_back(i);
}
int fd_p(int p ,int a ,int b){ // find the first number in the range [a,b] which is divisible by prime p
/* while(1){
if(a % p == 0 && a !=p) break;
a++;
}
return a;
*/
if(a != p){
return (a + mod(-a,p)) ;
}
else{
return (a + p);
}
}
void seg_sieve(int a , int b){
if(b < 2 ){
cout << "" ;
return;
}
if(a < 2){
a = 2;
}
int i,j;
int seg_size = b - a + 1;
int*is_prime = new int[seg_size];
memset(is_prime,0,seg_size*sizeof(int));
vector<int> :: iterator p ;
for(p = pv.begin(); p!=pv.end(); p++){
int x = fd_p(*p,a,b);
for(i = x; i <= b; i += *p )
is_prime[i - a] = 1;
}
for(i=0; i < b - a + 1; i++)
if(!is_prime[i])
printf("%u\n", i + a);
delete []is_prime ;
}
int main()
{
sieve();
int a,b,T;
scanf("%d",&T);
while(T--){
scanf("%d%d",&a,&b);
seg_sieve(a,b);
printf("\n");
}
// cout<<endl;
// system("PAUSE");
return 0;
}
尽管如此,我还是得到了 TLE .. 我不明白还需要什么其他优化。请帮助..
编辑1:只是试图在恒定时间内实现 fd_p() ... [失败] .. plz 如果你能帮助我解决这个错误..
编辑 2:问题已解决。