-1

I wrote this code for Sieve Of Eratosthenes but it is giving compile time error on ios_base::sync_with_stdio(false);.

The code is executing when I remove that line.

#include<bits/stdc++.h>
using namespace std;

ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);

void sieveOfEratosthenes(int n) {
  bool prime[n + 1];
  memset(prime, true, sizeof(prime));
  for (int p=2; n>=p*p; p++) {
    if (prime[p]) {
      for (int i = p*p; i<=n; i+=p)
        prime[i] = false;
    }
  }

  for(int p=2; p<=n; p++)
    cout <<p << " ";
}

int main() {
  cout << "Hello World!\n";
  int n;
  cout << "Please enter an integer n\n";
  cin >> n;
  sieveOfEratosthenes(n);
}
ocrdu
  • 2,172
  • 6
  • 15
  • 22
  • Put it in your `main` function. – DarthQuack Dec 24 '20 at 11:08
  • 1
    You have fallen into the [cargo cult](https://en.wikipedia.org/wiki/Cargo_cult_programming) of so-called "competitive" programming: Just copy from someone else without bothering to understand the code you're copying. You usually don't need that *boiler-plate* code presented by such sites. Also read [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) and [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Some programmer dude Dec 24 '20 at 11:09
  • 1
    Not to mention that they don't actually each you C++ or good programming habits. Don't use such sites to learn programming or C++. Get [some good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and take classes. – Some programmer dude Dec 24 '20 at 11:10
  • 1
    bool prime[n+1] is not valid c++ btw, it's an extension – Yamahari Dec 24 '20 at 11:10
  • Try to move `ios_base::sync_with_stdio(false);` into `main()` –  Dec 24 '20 at 11:59
  • That `memset` is also highly suspect. It makes implicit assumptions about the size and representation of `bool` objects. Use [`std::fill`](https://en.cppreference.com/w/cpp/algorithm/fill) instead. – Pete Becker Dec 24 '20 at 14:14

1 Answers1

0

Moving

ios_base::sync_with_stdio(false);
 cin.tie(0);
 cout.tie(0);

into main function worked :)