forked from shrox/Random-Codes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSieve_of_Eratosthenes.cpp
50 lines (44 loc) · 1.04 KB
/
Sieve_of_Eratosthenes.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include<iostream>
#include<bitset>
using namespace std;
int primes[3000100]; //list of primes
bitset <30000000> P; //instant prime check with boolean table
void generate( int N ) //sieve
{
P[2] = 1;
primes[0] = 2; //set 2 as prime
bool prime;
int ct = 1, i, j;
for ( i = 3; i <= N; i++ ) //range to sieve
{
prime = true;
for ( j = 0; primes[j]*primes[j] <= i; j++ ) //loop through previous primes until root of current number to check
{
if ( i % primes[j] == 0 )
{
prime = false; //not prime
break;
}
}
if ( prime )
{
primes[ct] = i; //add to list of primes
ct++;
P[i] = true; //add to boolean table
}
}
}
int main()
{
int N;
cin>>N; //specify range
generate(N);
while ( 1 )
{
cout<<"Enter 0 to end loop or N to check if N is prime:\n";
cin>>N;
if ( !N ) break;
P[N] ? cout<<"Yes\n" : cout<<"No\n";
}
return 0;
}