Search code examples
c++primessieve-of-eratosthenes

Why is my Sieve of Eratosthenes giving some composite numbers?


So, after running my implementation of the Sieve of Eratosthenes, for some cases, it also gives me composite numbers.

Eg.

When the limit of numbers is 10, I get, 2, 3, 5, 7, and 9 too.

When the limit is 30, I get 25 along with the prime numbers.

Why is this? My code is:

#include <iostream>
#include <cmath>
#include <vector>
using namespace std;

long long n;

int main()
{
    cout << "Till what number to find primes of?" << endl;
    cin >> n;
    int m = sqrt(n);
    vector<bool> prime(n+1, true);
    for(int i = 2; i<m; i++)
    {
        if(prime[i])
        {
            for(int k=i*i; k<=n; k=k+i)
            {
                prime[k] = false;
            }
        }
    }
    for(int j=2; j<=n; j++)
    {
        if(prime[j])
        {
            cout << j << endl;
        }
    }
    return 0;
}

Solution

  • Because you are checking for i < m rather than i <= m, so you never check the square root of 9, of 25 etc.
    Change

    for(int i = 2; i<m; i++)
    

    to

    for(int i = 2; i<=m; i++)