constatar
constatar

Reputation: 21

Prime number finder cannot find prime, stops after 7

So I made a simple prime number finder for the numbers between 3 and 200. It has to use a boolean variable, just fyi. No errors occur. output is:

The prime numbers between 3 and 200 are:
3
5
7

Why does it not keep going? I have drawn it out on paper time and again and cannot find my logic error.

In addition; I wrote this out by hand because I do not know how to get the contents of my file. It exists on a remote host which I do not have root access to. Is there a better way to copy the file?

#include <iostream>
using namespace std;

int main()
{
int count=0;
cout<<"The prime numbers between 3 and 200 are: "<<endl;

for (int i=3;i<=200;i++)
    {
     for (int j=2;j<i;j++)
        {
           bool ptest=i%j;
           if (!ptest)
             {
               break;
             }
           else if (ptest)
             {
                count=count+1;
                if (count==(i-2))
                cout<<i<<endl;
             }
         }
    }
}

Upvotes: 2

Views: 99

Answers (3)

Kristijan Iliev
Kristijan Iliev

Reputation: 4987

You don't have to loop till j reach i, instead you can check if j < sqrt(i) ,i.e. write in the second for loop: for (int j=3; j*j<=i; j+=2)

Upvotes: 0

R Sahu
R Sahu

Reputation: 206667

Some things to consider:

  1. You don't need to consider any even numbers in your code.

  2. You have some logic errors in your code. The value of count needs to be checked after the second for loop. count needs to be reset before the second for loop begins.

  3. You can stop immediately after you find the number is not prime in the inner loop instead of continuing on. You can just use a flag isPrime instead of counting.

Here's a version of the code that works for me:

#include <iostream>
using namespace std;

int main()
{
   cout << "The prime numbers between 3 and 200 are: " <<endl;

   for (int i=3; i <= 200; i += 2) {
      bool isPrime = true;
      for (int j=3; j < i; j += 2) {
         if (i % j == 0) {
            isPrime = false;
            break;
         }
      }

      if (isPrime)
      {
         cout << i << endl;
      }
   }
}

Upvotes: 0

M.M
M.M

Reputation: 141618

You forgot to set count back to 0 after using it in the j loop. Move the line:

int count = 0;

to be inside the first for loop. Then your program works correctly (although as msw indicated, it is not the most efficient technique!)

Upvotes: 1

Related Questions