Search
 
SCRIPT & CODE EXAMPLE
 

CPP

segmented sieve cpp

/// 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 :: find primes in a range in c++ 
Cpp :: check if character is uppercase c++ 
Cpp :: round up 2 digits float c++ 
Cpp :: vector search by element 
Cpp :: initialize an array in c++ 
Cpp :: c++ 
Cpp :: how to convert string into lowercase in cpp 
Cpp :: remove element from array c++ 
Cpp :: count number of set bits C++ 
Cpp :: c++ read each char of string 
Cpp :: ViewController import 
Cpp :: update variable in const function C++ 
Cpp :: how to use char in c++ 
Cpp :: joins in mysql use sequelize 
Cpp :: cout hex c++ 
Cpp :: check if set contains element c++ 
Cpp :: back() in c++ 
Cpp :: c++ print binary treenode 
Cpp :: for loop f# 
Cpp :: modulo subtraction 
Cpp :: pointer in return function c++ 
Cpp :: getline(cin string) not working 
Cpp :: integer to char c++ 
Cpp :: c preprocessor operations 
Cpp :: error handling in c++ 
Cpp :: c++ compile to exe command line 
Cpp :: c++ clip values 
Cpp :: c++ exceptions 
Cpp :: c++ reverse part of vector 
Cpp :: c++ template 
ADD CONTENT
Topic
Content
Source link
Name
7+7 =