C++ Prime numbers

So basically like anyone else here in the forum I've been having troubles coding this problem.

A prime number is a number that has only two factors, that is one (1) and itself. Create a flowchart and C++ program that will generate the first ten Prime numbers.

The first ten prime numbers are: 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29

Here's what I have so far
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  #include <iostream>
using namespace std;
int main()
{
	int check, check2, ctr;
	check = 1;
	check2 = 2;
	ctr = 0;
	   do{
	   	check++;
	   	   if(ctr>10)
	   	      return 0;
	   	   else if(check>=1 && check<=3)
			  cout<<check<<endl; 
			  ctr++;
		      if(check!=check/2*2)
		      do{
		      	check2++;
		      	   if(check==check2)
		      	      cout<<check<<endl;
					  ctr++;
		      } while((check%check2==0)||(check%check2!=0));  
	   }while((check>=1 && check<=3)||(check%check2!=0)||(check==check/2*2)||(ctr<=10));
}
Algo
1
2
3
4
5
6
7
8
-start
-count = 0
-for(i = 2; to ever)
    -if(i is a prim number)
        -add count by 1
     if(count == 10)
        break;
-end

First of all - please fix your formatting. It's a bit ugly.
Secondly, if I were to find primes, I would do it like that(pseudocode):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//Create array of primes
arrayOfPrimes;
arrayOfPrimes[0] = 2;
arrayOfPrimes[1] = 3;
count = 1;//Count of primes in array - 1(indexing from 0)
//While we haven't found as many primes as we want
while(count < 10)
{
   i = arrayOfPrimes[count] + 1;//We will be checking from last prime we found, + 1.
   if(isPrime(i))//If the number is prime
   {
     count++;//Update counter
     arrayOfPrimes[count] = i; // Pass new number to array
   }
   else
     ++i; // Else update number
}

And you check if the number num is prime by checking if any number from 2 to sqrt(num) divides it evenly.

If you want to optimize, you may want to see that even numbers can't be prime numbers, so instead of updating by 1, you can update by 2.
Last edited on
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
#include <iostream>
using namespace std;

bool isPrime(int);

int main()
{
	const int max = 10;
	int count = 0;
	
	cout<<"The first "<<max<<" primes are"<<endl;
	for(int i = 2;; i++)
	{
		if(isPrime(i))
		{
			count++;
			cout<<i<<" ";
		}
		if(count == max)
			break;
	}
	return 0;
}
bool isPrime(int x)
{
	for(int i = 2; i <= x/2; i++)
		if(x%i == 0)
			return false;
	return true;
}
Topic archived. No new replies allowed.