I would be glad if you could help and tell me where the problem is in the code:

#include <iostream> #include <string> using namespace std; int main() { int n,i; cin >> n; while ( i<=n ) { if ( i%2 != 0 && i%2 != 0 && i%2 != 0 ) { cout<<'prime number are: '<< i << endl; } else { return 0; } } } 
  • one
    The problem is that you don’t have a verification code for simplicity. The second problem is an endless loop. - Vladimir Martyanov
  • one
    Is the third problem a non-initialized variable? - pavel
  • To find prime numbers less than a given one, you can use the sieve of Eratosthenes - jfs
  • can pls code? - GrandPa

2 answers 2

Here is an example.

 #include <iostream> #include <vector> using namespace std; int main() { int x; cin >> x; vector<bool> arr; for (int i = 0; i < x; i++) arr.push_back(true); for (int i = 2; i < x; i++) { if (arr[i]) { cout << i << " "; for (int j = i; j < x; j = j + i) arr[j] = false; } } return 0; } 
  • And why are you arr[i] doing a false check after checking? Let the array is no longer needed, but why spoil it? - Mikhailo
  • @Mikhailo arr[j] = false; ? So I set all the numbers that are divisible by i to false , and if you mean that I did not write for (int j = i + i; j < x; j = j + i) - then you are absolutely right. - Timofey Pavlishinets

The easiest way, perhaps, is something like this:

 int main() { unsigned int N; cin >> N; if (N <= 2) return 0; cout << "2\n"; vector<bool> p(N,true); p[0] = p[1] = false; for(unsigned int i = 4; i < N; i+= 2) p[i] = false; for(unsigned int j = 3; j < N; j+=2) { if (p[j] == false) continue; cout << j << "\n"; if (j*j < N) for(unsigned int i = 2; i*j < N; ++i) p[i*j] = false; } }