mirror of
https://hub.njuu.cf/TheAlgorithms/C-Plus-Plus.git
synced 2023-10-11 13:05:55 +08:00
Update sieve_of_Eratosthenes.cpp
Multiple changes: Time complexity updated. Fixed Indentation issues. Global array primes[ ] was misleading because primes[x] = 0 means x is prime. Updated the array name to isprime[ ] and now isprime[x] = 1 means x is prime. Updated the code accordingly.
This commit is contained in:
parent
24794d8f08
commit
28e4842319
@ -2,7 +2,7 @@
|
|||||||
* Sieve of Eratosthenes is an algorithm to find the primes
|
* Sieve of Eratosthenes is an algorithm to find the primes
|
||||||
* that is between 2 to N (as defined in main).
|
* that is between 2 to N (as defined in main).
|
||||||
*
|
*
|
||||||
* Time Complexity : O(N)
|
* Time Complexity : O(N * log N)
|
||||||
* Space Complexity : O(N)
|
* Space Complexity : O(N)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@ -11,33 +11,33 @@ using namespace std;
|
|||||||
|
|
||||||
#define MAX 10000000
|
#define MAX 10000000
|
||||||
|
|
||||||
int primes[MAX];
|
int isprime[MAX];
|
||||||
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* This is the function that finds the primes and eliminates
|
* This is the function that finds the primes and eliminates
|
||||||
* the multiples.
|
* the multiples.
|
||||||
*/
|
*/
|
||||||
void sieve(int N)
|
void sieve(int N) {
|
||||||
{
|
isprime[0] = 0;
|
||||||
primes[0] = 1;
|
isprime[1] = 0;
|
||||||
primes[1] = 1;
|
for (int i = 2; i <= N; i++) {
|
||||||
for(int i=2;i<=N;i++)
|
if (isprime[i]) {
|
||||||
{
|
for (int j = i * 2; j <= N; j += i) {
|
||||||
if(primes[i] == 1) continue;
|
isprime[j] = 0;
|
||||||
for(int j=i+i;j<=N;j+=i)
|
}
|
||||||
primes[j] = 1;
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* This function prints out the primes to STDOUT
|
* This function prints out the primes to STDOUT
|
||||||
*/
|
*/
|
||||||
void print(int N)
|
void print(int N) {
|
||||||
{
|
for (int i = 1; i <= N; i++) {
|
||||||
for(int i=0;i<=N;i++)
|
if (isprime[i] == 1) {
|
||||||
if(primes[i] == 0)
|
|
||||||
cout << i << ' ';
|
cout << i << ' ';
|
||||||
|
}
|
||||||
|
}
|
||||||
cout << '\n';
|
cout << '\n';
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -45,14 +45,13 @@ void print(int N)
|
|||||||
* NOTE: This function is important for the
|
* NOTE: This function is important for the
|
||||||
* initialization of the array.
|
* initialization of the array.
|
||||||
*/
|
*/
|
||||||
void init()
|
void init() {
|
||||||
{
|
for (int i = 1; i < MAX; i++) {
|
||||||
for(int i=0;i<MAX;i++)
|
isprime[i] = 1;
|
||||||
primes[i] = 0;
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
int main()
|
int main() {
|
||||||
{
|
|
||||||
int N = 100;
|
int N = 100;
|
||||||
init();
|
init();
|
||||||
sieve(N);
|
sieve(N);
|
||||||
|
Loading…
x
Reference in New Issue
Block a user