Finding and displaying primes.

I need to write a program that finds and displays the first 20 prime numbers. My instructor explained it pretty well, so I'll just show the actual assignment:
Write program that displays the first 20 prime numbers. An integer greater than 1, is prime if it is only divisible by 1 and itself. For example 2, 3, 5, and 7 are prime numbers but 4, 6, 8 and 9 are not. To find out if a number is prime, check whether the number is divisible by 2, 3, 4, 5 .. up to number/2. If a divisor is found, the number is not a prime. The algorithm can be described as follows:

Use a boolean variable isPrime to denote whether the number is prime. Set isPrime to true initially.

1
2
3
4
5
6
7
8
for (divisor = 2; divisor < = number /2; divisor ++)
 {
   If (number % divisor == 0)
   {
    Set isPrime to false
    Exit the loop
   }
}


You must use nested loop for this program. The output of the program should be:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71


I've worked on it some, but it keeps printing tons of huge numbers. Here's my code so far:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;
int main ()
{
    int number=4, count=1;
    bool isPrime=true;
    
    for (int divisor = 2; divisor <= number/2; divisor++) 
    {
        for (int count=0; count<=20; count++) 
        {
            if ( number%divisor == 0)
            {
                isPrime=false;
            }
            cout << number << " ";
            number++;
        }
    }
    
    return 0;
}
Last edited on
It's up to youuu~!
Last edited on
There are a ton of threads on here that derive the logic for finding primes. Do a search.
Topic archived. No new replies allowed.