The sieve of Eratosthenes is an ancient algorithm for finding all the prime numbers to the given limit by excluding the multiples of the prime numbers (ex- 2,3,5,7)
Since the multiples of 4 are already removed, resume to next smallest prime number 5.
The next smallest prime number 11 is greater than the sqrt(100), therefore the process ceases.
List of Prime Numbers from 1 - 100
result = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
Code
#include <iostream>
#include <math.h>
using namespace std;
int N;
int D;
int total = 0;
int main()
{
cin >> N;
bool* isPrime = new bool[N];
D = sqrt(N);
for (int i = 1; i < N; i++)
{
isPrime[i] = true;
}
for (int i = 2; i <= D; i++)
{
if (isPrime[i] == true)
for (int j = i + i; j < N; j = j + i)
{
isPrime[j] = false;
}
}
for(int i = 2; i < N; i++)
{
if (isPrime[i] == true)
{
cout << i << ", ";
total = total + 1;
}
}
cout << endl;
cout << "# of Primes : " << total << endl;
return 0;
}
Output
100
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
# of Primes : 25
Code
def isPrime():
N = int(input())
sieve = [True] * N
limit = int(N ** 0.5)
for i in range(2, limit + 1):
if sieve[i] == True:
for j in range(i+i, N, i):
sieve[j] = False
return [i for i in range(2, N) if sieve[i] == True]
print(isPrime())
Output
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]