Search
 
SCRIPT & CODE EXAMPLE
 

CPP

primes in range 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 :: c++ cout colored output xcode 
Cpp :: not in c++ 
Cpp :: sleep c++ 
Cpp :: how to store pair in min heap in c++ 
Cpp :: overload stream extract cpp 
Cpp :: when was c++ created 
Cpp :: docker.io : Depends: containerd (= 1.2.6-0ubuntu1~) E: Unable to correct problems, you have held broken packages 
Cpp :: how to get the first element of a map in c++ 
Cpp :: change int to string c++ 
Cpp :: c++ isalphanum 
Cpp :: index string c++ 
Cpp :: file c++ 
Cpp :: 2-Dimensional array in c++ 
Cpp :: c++ remove text file 
Cpp :: string to uint64_t c++ 
Cpp :: time of a loop in c++ 
Cpp :: c++ array size 
Cpp :: cpp string slice 
Cpp :: draw rectangle opencv c++ 
Cpp :: sizeof’ on array function parameter ‘arr’ will return size of ‘int*’ [-Wsizeof-array-argument] 
Cpp :: print vector c++ 
Cpp :: how to add c++14 in sublime text 
Cpp :: erase element from vector c++ 
Cpp :: cpp class constructor 
Cpp :: pure virtual function in c++ 
Cpp :: login system with c++ 
Cpp :: insert in vector 
Cpp :: cpp map insert 
Cpp :: how to use a non const function from a const function 
Cpp :: c++ function of find maximum value in an array 
ADD CONTENT
Topic
Content
Source link
Name
9+9 =