10001 prime number code

I try to resolve the following problem:
________________________
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10 001st prime number?
__________________

To solve this problem I did the following code, but after I compile and run
only appear the black window without nothing in it.

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;

bool isPrime( int n )
{
    int counter = 0;

    for( int divisor = 1; divisor <= n; ++divisor )
        {
            if( n % divisor == 0 )
            {
                ++counter;
            }
        }
    if( counter == 2 )
        return true;
    else
        return false;
}

int main()
{
    unsigned long primeIwant = 1;
    long primeRank = 0;

    while( primeRank <= 10001 )
        {
            primeIwant += 1;

            if( isPrime( primeIwant ) == true )
                ++primeRank;
        }

    if( primeRank == 10001 )
        cout << primeIwant;

      return 0;
}
Last edited on
Your program is running, it is just taking a long time ;)
Well ... it seems that there is something wrong... because even waiting a long time I did not get the right answer
Last edited on
Check your while loop condition. Think: which prime number will the loop stop for?
omg... now I'm as bugged as the program
Did you get an answer? Your algorithm is inefficient. If you didn't get an answer, try changing the limit from 10001 to 100 then 500 then 1000 then 5000. I think you'll find that it takes longer and longer and loooooonnnnnngggggggeeeeerrrrr.... :)
Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool isPrime( int n )
{
    int counter = 0;

    for( int divisor = 1; divisor <= n; ++divisor )
        {
            if( n % divisor == 0 )
            {
                if( counter > 0 )
                  return false;
                ++counter;
            }
        }
        return true;
}
to shorten the runtime.
Hi,

Is this for an on-line coding challenge like Euler or on-line judge ?

If so, these problems are not solved by brute force - one has to come up with a cunning plan instead.

Google and wiki are your best friends. At the bottom of the wiki page there is Euler's algorithm - which is a specialisation of sieves of Eratosthenes.

Also Google fast prime number algorithms.

Enjoy :+)
Topic archived. No new replies allowed.