Search code examples
c++visual-studio-codeprimes

Code Not working in VS Code but works in OnlineGDB


I am practicing about primeSieve with C++ language in VS Code 1.57.1.

But the attached code doesn't show output in VS Code while it shows output in online c++ compiler like https://www.onlinegdb.com/online_c++_compiler

Can anyone help me to resolve this issue.

#include<iostream>
using namespace std;
void primeSieve(){//Genearate array containing prime number
    int number;
    cin>>number;
    int p[1000] = {0}; //1=Prime;0=Non-Prime
    
    //Mark All Odd number prime
    for(int i=3;i<=1000;i+=2){
        p[i]=1;
    }
    //Sieve
    for(int i=3;i<=1000;i+=2){//jumping over odd numbers
        //if current number is not marked(it is prime)
        if(p[i]==1){
            //Mark Multiples as 0
            for(int j=2*i;j<=1000;j=j+i){
                p[j]=0;
            }
        }
    }
    //Special Case
    p[2]=1;
    p[1]=p[0]=0;

    for(int x=0;x<=number;x++){
        if(p[x]!=0){
            cout<<x<<" ";
        }
    }
}
int main(){
    primeSieve();
    return 0;
}

Solution

  • Size of p[] is 1000. Your loop goes up to 1000. Try removing the = in the loops and just keep i < 1000.