Pagini recente » Cod sursa (job #1780403) | Cod sursa (job #1680953) | Cod sursa (job #3260514) | Cod sursa (job #382070) | Cod sursa (job #806584)
Cod sursa(job #806584)
#include <fstream>
#include <iostream>
#include <cmath>
using namespace std;
ifstream in("ciur.in");
ofstream out("ciur.out");
class Eratosthenes{
int n;
int *lowerPrimes; // un vector ce va tine numarul de nr prime mai mici decat n
int *sieve; // will basically act as a bitmap, a nr will be prime if its corresponding bit is 0
int bits[35]; // bit i will be 2 to the power of i
inline void set(int x){
int posInt=x/32;
int posBit=x%32;
sieve[posInt]|=bits[posBit];
}
inline bool isSet(int x){
int posInt=x/32;
int posBit=x%32;
return sieve[posInt]&bits[posBit];
}
public:
Eratosthenes(int);
void createLowerPrimes();
int countPrimes(int);
};
Eratosthenes::Eratosthenes(int value){
int i,j;
n=value;
sieve=new int[(n>>5)+1];
for(i=0;i<=(n>>5);++i)
sieve[i]=0;
bits[0]=1;
for(i=1;i<32;++i)
bits[i]=bits[i-1]<<1;
for(i=4;i<=n;i+=2)
set(i);
for(i=3;i*i<=n;i+=2){
if(!isSet(i)){
for(j=i*i;j<=n;j+=i){
set(j);
}
continue;
}
}
}
void Eratosthenes::createLowerPrimes(){
int i;
lowerPrimes=new int[n+1];
lowerPrimes[0]=lowerPrimes[1]=0;
for(i=1;i<=n;++i){
if(!isSet(i)){
lowerPrimes[i]=lowerPrimes[i-1]+1;
continue;
}
lowerPrimes[i]=lowerPrimes[i-1];
}
}
int Eratosthenes::countPrimes(int value){
int counter=0;
for(int i=2;i<=n;++i){
if(!isSet(i)){
counter++;
}
}
return counter;
}
int main(){
int n;
in>>n;
Eratosthenes ciur(n);
out<<ciur.countPrimes(n);
return 0;
}