Pergunta

    #include <iostream> 
    using namespace std;



    int main () 
    {
       int count = 0;

          for (int x=2; x < 100; x++)

              for (int y=2; y < x; y++)
              {

                 if (x % y == 0) 
                 break;
                 else if (x == y + 1)
                      count++;
                      cout << x << " ";

       cout << count;
       system("pause")
       return 0;




    }

I want to print the prime numbers and also print out the number of prime numbers between 2 and 100. which should be 24. Instead I get a ton of repeats of the prime numbers and then the number 24. I'm sure it's a logical error, just not catching it.

Foi útil?

Solução

First, there are syntax errors.

Second, always use curly braces with if/else unless you know what you are doing - there's an error related to this.

Third, using system() requires #include <cstdlib>. Your compiler is lax if it allows you to not to (g++ doesn't).

Fourth, pause is not a standalone program but a cmd.exe builtin so system() may fail depending on the compiler/environment used. A neater way is C++ keypress: getch, cin.get? .

Finally, your algorithm is highly suboptimal. E.g. y only needs to go up to x/2+1 and it's reasonable to store the primes already found in an array/list and try only them.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top