Segmented Sieve of Eratosthenes?

后端 未结 5 461
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 13:15

It\'s easy enough to make a simple sieve:

for (int i=2; i<=N; i++){
    if (sieve[i]==0){
        cout << i << \" is prime\" << endl;
           


        
5条回答
  •  忘了有多久
    2020-11-22 13:34

    If someone would like to see C++ implementation, here is mine:

    void sito_delta( int delta, std::vector &res)
    {
    
    std::unique_ptr results(new int[delta+1]);
    for(int i = 0; i <= delta; ++i)
        results[i] = 1;
    
    int pierw = sqrt(delta);
    for (int j = 2; j <= pierw; ++j)
    {
        if(results[j])
        {
            for (int k = 2*j; k <= delta; k+=j)
            {
                results[k]=0;
            }
        }
    }
    
    for (int m = 2; m <= delta; ++m)
        if (results[m])
        {
            res.push_back(m);
            std::cout<<","< &fiPri)
    {
    int delta = sqrt(n);
    
    if (delta>10)
    {
        sito_segment(delta,fiPri);
       // COmpute using fiPri as primes
       // n=n,prime = fiPri;
          std::vector prime=fiPri;
          int offset = delta;
          int low = offset;
          int high = offset * 2;
          while (low < n)
          {
              if (high >=n ) high = n;
              int mark[offset+1];
              for (int s=0;s<=offset;++s)
                  mark[s]=1;
    
              for(int j = 0; j< prime.size(); ++j)
              {
                int lowMinimum = (low/prime[j]) * prime[j];
                if(lowMinimum < low)
                    lowMinimum += prime[j];
    
                for(int k = lowMinimum; k<=high;k+=prime[j])
                    mark[k-low]=0;
              }
    
              for(int i = low; i <= high; i++)
                  if(mark[i-low])
                  {
                    fiPri.push_back(i);
                    std::cout<<","< prime;
    sito_delta(delta, prime);
    //
    fiPri = prime;
    //
    int offset = delta;
    int low = offset;
    int high = offset * 2;
    // Process segments one by one 
    while (low < n)
    {
        if (high >= n) high = n;
        int  mark[offset+1];
        for (int s = 0; s <= offset; ++s)
            mark[s] = 1;
    
        for (int j = 0; j < prime.size(); ++j)
        {
            // find the minimum number in [low..high] that is
            // multiple of prime[i] (divisible by prime[j])
            int lowMinimum = (low/prime[j]) * prime[j];
            if(lowMinimum < low)
                lowMinimum += prime[j];
    
            //Mark multiples of prime[i] in [low..high]
            for (int k = lowMinimum; k <= high; k+=prime[j])
                mark[k-low] = 0;
        }
    
        for (int i = low; i <= high; i++)
            if(mark[i-low])
            {
                fiPri.push_back(i);
                std::cout<<","< fiPri;
    sito_segment(1013,fiPri);
    }
    

提交回复
热议问题