advice: finding the nth prime numbers

Hi, any advice would be appreciated.
Currently this program has a lot of problems and I think I'm probably going about doing it all wrong.

what I'm trying to figure out is for the user to enter a number, say 5, and the program should display the first five prime numbers starting from two: 2, 3, 5, 7, and 11 in that case.

Program has lot of issues and doesn't filter out all non prime numbers.

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
#include <iostream>
using namespace std;
 
int main() {

	int MAX; 
     cout<<"How many prime numbers do you want to display?"<<endl; 
	 cin>>MAX;
	 if (MAX==-1){exit(1);}//Entering -1 will exit the program

		/////////////////////////////////////////////////
		int U;  

	for (float x=2; x<= MAX; x++)//modifies the number being tested. 

	{
	int v=int(x); 
	int k=sqrt(x); 

		for (int q=2; q <= k; q++)
		{
			while (q==k){
			if (v%q==0) break; 
			else {cout<< v <<" Is a prime number"<<endl; } 
			break; 
		}


		/////////////////////////////////////////////////
	}

}
	


system ("pause"); 
return 0;
}


thanks
Last edited on
Hi frog030,

for (float x=2; x<= MAX; x++)

for (int q=2; q <= k; q++)

You shouldn't use floats in a for loop like that. They can't be represented exactly so nearly always fail.

I think there is confusion about the types you are using.

Edit:
int k=sqrt(x);

If you want to cast to an int:
int v=int(x);

then it should look like this:

int v=(int)x;


Edit2: 5 is a prime number !!
Last edited on
Reworked the code a bit. Making some progress, but still not working like I want it to.

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
#include <iostream>
#include <conio.h>
 
using namespace std;
 
int main() {

	int MAX; 
     cout<<"How many primes to you wish to display?"<<endl; 
	 cin>>MAX;
	 if (MAX==-1){exit(1);}

	int rep=2;
	while (rep<=MAX){ 
	bool prime (true); 
	 ////////////////////////////////////////////////////
	int input=rep; 
	for (int i = 2; i < input/2 && prime; i++)
        prime = !(input%i == 0);
	if(prime==true){cout<<input<<" is prime"<<endl; rep++; }
	else{cout<<input<<" is not prime"<<endl; rep ++; } 

    ////////////////////////////////////////////////////
	 }

	system ("pause"); 
	return 0;
	}
Topic archived. No new replies allowed.