Search
 
SCRIPT & CODE EXAMPLE
 

CPP

c++ segmented sieve

/// Using Segmented Sieve to find Primes within a range (l..r)
/// Constaints: 1<=l<=r<=10^12, r-l<=10^6

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <bitset>

using namespace std;

#define ll long long
#define llu unsigned long long
#define endl "
"
#define pb push_back

#define N 1000000

typedef vector <ll> vi;

bitset < N + 1 > numbers;
vi primes;
void sieve(){
    numbers.set();
    numbers[1] = 0;
    
    for (ll i = 2; i<N; i++){
        if (numbers[i] == 1){
            primes.pb(i);
            for (ll j = i*i; j<N; j+=i){
                numbers[j] = 0;
            }
        }
    }
}

int main(){
  
    sieve();

    ll t;
    cin>>t;
    
    while (t--){
        ll l,r;
        cin>>l>>r;
        
        float tmpSqrt = sqrt(r);
        ll sqrtR = (ll)tmpSqrt;
        if (tmpSqrt != (float)sqrtR)
            sqrtR++;
        
        ll lastPrimeIndexInRange = 0;
        while (primes[lastPrimeIndexInRange] <= sqrtR)
            lastPrimeIndexInRange++;
        
        numbers.set();
        if (l == 1)
            numbers[0] = 0;
        
        for (llu i = 0; i<lastPrimeIndexInRange; i++){
            
            ll firstMulti = (l/primes[i]) * primes[i];
            if (firstMulti < l)
                firstMulti += primes[i];
            
            for (ll j = max(firstMulti, primes[i] * primes[i]); j<=r; j+= primes[i])
                numbers[j-l] = 0;
        }
        
        for (ll i = 0; i<r-l+1; i++)
            if (numbers[i] == 1)
                cout<<i + l<<endl;
        cout<<endl;
    }
    
	return 0;
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: check uppercase c++ 
Cpp :: round up 2 digits float c++ 
Cpp :: how to do sets in cpp 
Cpp :: C++ array sort method 
Cpp :: get window position 
Cpp :: Story of c++ 
Cpp :: Parenthesis Checker using stack in c++ 
Cpp :: arduino funktion 
Cpp :: increment c++ 
Cpp :: delete specific row from dynamic 2d array c++ 
Cpp :: c++ check palindrome 
Cpp :: time_t to int 
Cpp :: upcasting in c++ 
Cpp :: c++ Sum of all the factors of a number 
Cpp :: c++ string element access 
Cpp :: function c++ 
Cpp :: initialize vector of vector c++ 
Cpp :: sort a vector c++ 
Cpp :: sizeof operator in c++ 
Cpp :: how to search in array c++ 
Cpp :: c++ hashmaps 
Cpp :: c++ struct 
Cpp :: remove element from vector c++ 
Cpp :: c define 
Cpp :: c++ erase remove 
Cpp :: C++ New Lines 
Cpp :: inserting element in vector in C++ 
Cpp :: how to concatenate two vectors in c++ 
Cpp :: c++ random number 
Cpp :: how to add space in c++ 
ADD CONTENT
Topic
Content
Source link
Name
2+7 =