Finding Prime Numbers from 1-100. So close!

I'm so close to finishing this program. All need to do is output 2, 3, 5 because those are prime numbers as well(the only numbers left to output). How could I modify my code to output those numbers as well.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
  #include <iostream>

using namespace std;

void PrimeNumber(int &);

int main()
{
    int totalPrimeNumber = 0;

    cout << "How many prime numbers do you want to display? " << endl;
    cout << "\nNote, can only be numbers from 1-100. ";
    cin >> totalPrimeNumber;

    while( totalPrimeNumber < 1 || totalPrimeNumber > 100)
    {
        cerr << "\nError, outside of the domain of valid numbers. ";
        cin >> totalPrimeNumber;
    }

    PrimeNumber(totalPrimeNumber);

    return 0;
}

void PrimeNumber(int &x)
{
    int currentNumber =1;
    int counter = 0;

    while(counter < x)
    {
        currentNumber++;

        if((currentNumber / currentNumber == 1) && (currentNumber / 1 == currentNumber)
            && (currentNumber % 2 != 0) && (currentNumber % 3 != 0) && (currentNumber % 5 != 0))
        {
            counter++;

            cout << currentNumber << "  ";
        }
    }
}
Last edited on
I'm so close to finishing this program. All need to do is output 2, 3, 5 because those prime numbers as well.

You could just print those prior to the others. Your algorithm, though, is not correct. Is 49 a prime number?
oops, yes you're correct I overlooked that.
This won't find just prime numbers; for example, this program would print out 49 even though 49 isn't a prime number.

This is also the reason your code won't output 2, 3, and 5. When checking if the number is prime, instead of checking if it is divisible by 2, 3, and 5, you should use a for loop to go from 1 to the num/2 to ensure that the number is in fact prime. You should also have a boolean to see if its prime. You could make this another function or
you could put it inside the same function.

Your code would look something like this:

while( counter < x){

currentNumber++;
bool prime = true;

for(int i = 2; i < currentNumber / 2; i++){

if(currentNumber % i == 0)
prime=false;

}

if (prime == true)
cout << currentNumber << " ";
}
Last edited on
I need to find a way to check for those two parameters and also if that number has more than 2 divisors.
Topic archived. No new replies allowed.