Prime Test Program

Hi

So I have this assignment in which I must create a prime test code in C++ to determine if a number is prime. To indicate a number is prime, the number 1 must be output and if it is not prime the number 0 is output. I would really appreciate on feedback on how to fix it. I really don't want the exact code written out, I really want to get into Software Engineering so any explanations on what I should fix would be great.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

int main()
{

    int number;
    int count;
    cin >> number;

    for (int i=2;i<number;i++){
        if (number%i == 0)
            count++;
    }

    if (count >1)
        cout << 0 << endl;
    else if (count == 0)
        cout << 1 << endl;
    return 0;
}
Last edited on
When you compile, make sure you have warnings enabled. You should get a warning saying something like 'count' may be used uninitialized in this function.

Basically, line 10 says you are declaring an integer called count, but not what value it has. So, it could be (and likely will be) a ridiculously large number or ridiculously small negative number.

To fix, change line 10 to int count = 0;.

On another note, your program could be a lot more efficient, like not continuing the loop when you already know it's not a prime number, but I don't think it matters for your case.
Last edited on
Thank you for the reply

I have made a mistake in the original post and forgot to add the int count = 0; as I was in a hurry a bit.

But another problem is my instructor had given me a list of numbers to input into the code via gvimdiff and when I run it I just get a bunch of ----- red dotted lines running across for every line. Do you happen to know how I can fix this?
Topic archived. No new replies allowed.