Q
Q
qwerttt12122018-06-16 21:34:02
C++ / C#
qwerttt1212, 2018-06-16 21:34:02

Output of prime numbers from 0 to 1000. Where is the error in the code?

#include<iostream>
using namespace std;
int main() {
  int n, p;
  p = 2;
  for (n = 1; n < 1000; n++) {
    bool prime = true;
    for (p; p < n; p++) {
      if (n % p == 0) {
        prime = false;
      }
    }
    if (prime == true) {
      cout << n << " - Prostoe" << endl;
    }
    else {
      cout << n <<" - Sostavnoe" << endl;
    }
  }
  system("pause");
  return 0;
}

Shows that all numbers are prime. Please help me find the error.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Espleth, 2018-06-16
@qwerttt1212

you don't have p returned to its original value anywhere. remove it from the 1st line (in general, loop variables should be defined in the loop itself) and do this:
for (int p = 2; p < n; p++)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question