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.
#include <iostream>
usingnamespace 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<x; i++)
{
if (x%i==0)
{
x = p;
n++;
if (n==y)
{
cout << y << ". prastevilo je " << p << "\n"; // The y. prime nubmer is p
break;
}
elsecontinue;
}
elsecontinue;
}
}
system("PAUSE");
return 0;
}
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
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.
#include <iostream>
usingnamespace 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<x; n++)
{
if (x % n != 0) //keeps track of the amt. of numbers not divisible
counter++;
if (counter == (x - 2)) //checks if all numbers were not divisible
{
p++;
if (p == y)
cout << x << " is the " << y << " prime number.\n";
}
}
}
return 0;
}