We had to find the prime numbers. How do you like that?

#include <iostream> using namespace std; int main(){ // Prosti numerics int n = 10,q = 0; cout << "2 3 5 7 "; while (q < 10) { n++; if (n%2 != 0) if (n%3!= 0) if (n%5!= 0) if (n%7!= 0) cout << n << " "; } return 0; } 
  • 3
    Congratulations! You learned how to program endless loops! - user194374
  • one
    why such nesting if? and 1 was never a prime number. - KoVadim
  • @KoVadim, oh, really) - goodalien
  • 2
    Why are you asking for forgiveness from numerics ? - ixSci

3 answers 3

There are a lot of bugs in the program. Part already indicated.

  • 1 is not a prime number
  • infinite loop (as also noted by @kff)
  • condition can be written easier.
  • finds not all prime numbers (after correcting the code)

Fix obvious errors

 #include <iostream> using namespace std; int main(){ // prime numerics int n = 10; cout << "2 3 5 7 "; while (n < 1000) { n++; if (n%2 != 0 && n%3!= 0 && n%5!= 0 && n%7!= 0) cout << n << " "; } return 0; } 

But even now, the program found a “prime number” 121 or 143, or 169 (and many many others that are not simple).

The “experts” condition itself can even be written like this (n%2 && n%3 && n%5 && n%7) , but I think this is already a bust.

  • And why brute force is not accepted or readability suffers? PS I instead of n% 2 got used to write n & 1. - pavel
  • It is possible to write & 1, but in this case it is better monotony. And the compiler has long been able to optimize it. - KoVadim
  • @KoVadim, &1 and %2 slightly different reaction to negative numbers. Therefore, I prefer &1 . - Qwertiy ♦
  • 2
    And you know a lot of negative prime numbers? - KoVadim
  • @pavel, and in vain. The code should convey its essence, and not be obfustsirovan something. - ixSci

Your code does not hold water. Here is the simplest code that computes prime numbers. The algorithm is terribly inefficient, but it works.

 #include <vector> #include <iostream> int main() { const unsigned max = 100; std::vector<unsigned> simple; for (unsigned n = 2; n <= max; ++n) { bool isSimple = true; for (size_t i = 0; i < simple.size(); ++i) { if (n % simple[i] == 0) { isSimple = false; break; } } if (isSimple) { simple.push_back(n); std::cout << n << std::endl; } } } 

PS Inefficiency, by the way, is relative. This algorithm applies to memory almost as economically as possible, but the speed of work leaves much to be desired. However, prime numbers up to a million calculates in less than a minute.

    long live the classic grate of Eratosthenes!

     #include <stdio.h> #include <cstdio> #define MAX 1000 using namespace std; bool prime[MAX + 2]; int main() { int p, d; prime[0] = prime[1] = 0; for (p = 3; p <= MAX; p += 2) prime[p] = true; for (p = 3; p*p <= MAX; p += 2) { if (prime[p]) for (d = p*p; d <= MAX; d += p) prime[d] = 0; } printf("2\n"); for (p = 3; p <= MAX; p += 2) { if (prime[p]) printf("%d\n", p); } return 0; }