10001 prime number code

Sep 1, 2015 at 11:00am
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 Sep 1, 2015 at 11:02am
Sep 1, 2015 at 11:10am
Your program is running, it is just taking a long time ;)
Sep 1, 2015 at 11:35am
Well ... it seems that there is something wrong... because even waiting a long time I did not get the right answer
Last edited on Sep 1, 2015 at 11:35am
Sep 1, 2015 at 11:40am
Check your while loop condition. Think: which prime number will the loop stop for?
Sep 1, 2015 at 11:56am
omg... now I'm as bugged as the program
Sep 1, 2015 at 12:01pm
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.... :)
Sep 1, 2015 at 12:03pm
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.
Sep 2, 2015 at 12:28am
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.