### Prime numbers in order

Greeting to all of you, who wish to help me.

I tried to make a program, in which you could say which prime number you wanted to know, for example the 23rd , and it would then tell you which prime number is the 23rd.

The theory goes like this:
You input the number, the program will check every prime number (excluding 2 and 3 so it would work a bit faster), and for every prime number it finds it would mark n as the n-th prime number. When n reaches the desired input, y in this matter, it would output the message "The y-th number is x".

I assume that I booched something up, or that my theory doesn't equal my program. Any help would be gladly appreciated.

And here's the code:
 ``12345678910111213141516171819202122232425262728293031323334353637383940414243`` ``````#include using namespace std; int main() { int p; int y; int n=2; cout << "Katero zaporedno prastevilo zelite izvedeti (vnesite samo stevilo):"; //"Which prime number in order do you want?" cin >> y; if (y==1) { cout << y << ". prastevilo je 2\n"; } if (y==2) { cout << y << ". prastevilo je 3\n"; } for(int x=5; x<10000; x+=2) // I, skipped 4 because it would be just a waste and I limited it to 10000 just for testing. { for(int i=3; i
Last edited on
Your condition on line 23 is wrong. If x%i==0, x is not a prime
Ah, that seemed to be one of the problems, but now any number that I put in like 4 or 5, it outputs the number 1991220788, for any number...
it's because p has no value, so it shows random number
Last edited on
How else could I track the number the program is testing?
you don't need p at all. Just print x. Or in your program p=x, not x=p
Last edited on
One problem fixed and another surfaces.
The good thing is that it actually works, but not as it should.
For the 3rd it outputs 5
For the 4th it outputs 7
For the 5th it outputs 7
For the 6th it outputs 9

I have no idea why it is doing this.
When I read this, I tried my own version of the same program just for practice. I ran into the exact same problem you did, and my code was almost identical. I did however get it to work, and this is what I came up with. Hope it helps. Also, didn't see the point of the else continues.

 ``12345678910111213141516171819202122232425262728293031323334353637`` ``````#include using namespace std; int main() { int y, p=2, n, counter; cout << "Which prime number do you want? "; cin >> y; if (y==1) cout << "2 is the first prime number"; if (y==2) cout << "3 is the second prime number"; for(int x=5; x<10000; x+=2) { counter = 0; for(n=2; n
Thank you, your code helped me a lot and now it finally works! :D
Topic archived. No new replies allowed.