-3

I recently learned Sieve of Eratosthenes to find prime numbers. After knowing the method i wrote this code for it.
Would it be a valid C++ code for Sieve of Eratosthenes?

#include <iostream>
using namespace std;

int main()
{
int n;
cin>>n;
bool array[n];

for(int i=2;i<=n;i++)
{
    array[i]=true;
}

   for(int i=2;i<=n/2;i++)
   {
      for(int j=i+1;j<=n;j++)
      {
         if(array[j]==true)
         {
            if(j%i==0)
            array[j]=false;
         }
      }
   }

  for(int k=2;k<=n;k++)
  {
    if(array[k]==true)
    cout<<k<<" ";
  }
}

Thanks for help!

Suyash
  • 39
  • 5
  • 3
    Does the code give the correct result? That would be an important first test. – Bart Jul 17 '18 at 15:34
  • 1
    bool array[n] is not something valid in cpp, and even if it would be, your loops are <= n which means you will read/write memory outside the boundaries of array[n]. Get a good book and an environment that lets you compile and use a debugger. – AlexG Jul 17 '18 at 15:34
  • No, arrays and vectors use zero based indexing. Did you try to run it? – JVApen Jul 17 '18 at 15:35
  • Yes, it gives correct output. – Suyash Jul 17 '18 at 15:36
  • 1
    No. If you compile it with warnings you'll see that the declaration of `array` isn't valid C++ because C++ doesn't have variable-length arrays and `n` is a variable. If you fix that (or set your compiler to allow VLAs), you run into undefined behavior because you access `array[n]`. Otherwise, I think you get the right answer but the algorithm is still wrong. You waste time crossing off the multiples of non-prime, checking `j` even though it doesn't matter (which doesn't affect the complexity but does slow you down), and incrementing `j` by 1 instead of by `i`, which does affect the complexity. – Daniel H Jul 17 '18 at 15:41
  • ***it gives correct output*** Unfortunately some times Undefined Behavior appears to work only to fail at random. – drescherjm Jul 17 '18 at 16:09

1 Answers1

2

No. This is not the Sieve of Eratosthenes. There is no division (j % i == 0) in the Sieve of Eratosthenes.

user448810
  • 17,381
  • 4
  • 34
  • 59