I was reading about algorithms the other day and came to know of a faster algorithm to find prime numbers. It is called the Sieve of Eratosthenes. When I compared the execution times of this algorithm to the one I coded, the times were remarkably faster. A very simple and impressive algorithm to find prime numbers less than a number n.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <ctime> | |
using namespace std; | |
//interesting method of finding primes | |
// saw this one in one of the algorithm books | |
void sieve_of_eratosthenes(int n) | |
{ | |
int a[n + 1]; | |
for (int i = 0; i <= n; i++) { | |
a[i] = 1; | |
} | |
for (int i = 2; i <= n / 2; i++) | |
for (int j = 2; j <= n / i; i++) | |
a[i * j] = 0; | |
for (int i = 2; i <= n; i++) | |
if (a[i]) { | |
cout << i << " is prime" << endl; | |
} | |
} | |
// the one I coded | |
void sieve_of_harpreet(int n) | |
{ | |
bool p; | |
for (int i = 2; i < n; i++) { | |
p = true; | |
//optimized by checking only until sqrt of the num | |
for (int j = 2; j * j < i; j++) { | |
if (i % j == 0) { | |
p = false; | |
break; | |
} | |
} | |
if (p) { | |
cout << i << " is prime" << endl; | |
} | |
} | |
} | |
int main() | |
{ | |
unsigned int start = clock(); | |
sieve_of_harpreet(30000000); | |
std::cout << "Time taken: " << clock() - start << endl; | |
start = clock(); | |
sieve_of_eratosthenes(30000000); | |
std::cout << "Time taken: " << clock() - start << endl; | |
return 0; | |
} |