0

The code gives me the answer 43739 which is wrong. I don't know which part of the code I messed up, help would be much appreciated.

        {
            int primenumbers = 4;
            int thenumber = 2;
            int finalnumber = 0;

            while (primenumbers <= 10001)
            {
                for (int x = 2; x < 10; x++)
                {
                    if (thenumber % x == 0)
                    {
                        x = 10;
                    }

                    if (x == 9)
                    {
                        finalnumber = thenumber;
                        primenumbers += 1;
                        break;
                    }
                }

                thenumber += 1;
            }

            Console.WriteLine(finalnumber);
        }
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
JW Ngiam
  • 5
  • 1
  • 3
    You don't check whether your prime numbers can be divided by numbers bigger than 10. – SomeBody Dec 07 '20 at 07:43
  • Take a look at https://stackoverflow.com/questions/15743192/check-if-number-is-prime-number – JonasH Dec 07 '20 at 07:44
  • 43739 is divisible by 191 and 229. Nothing smaller. – ProgrammingLlama Dec 07 '20 at 07:46
  • Your approach is also not generic with respect to the desired nth prime number. It doesn't work for the 4th prime for instance. As a general hint: try to make clear within your functions which constraints are required for a proper usage. – Secundi Dec 07 '20 at 07:55

1 Answers1

4

Let's split the initial problem into smaller ones: first, check for being prime:

   private static bool IsPrime(int value) {
     if (value <= 1)
       return false;
     else if (value % 2 == 0)
       return value == 2;

     int n = (int) (Math.Sqrt(value) + 0.5);

     for (int d = 3; d <= n; d += 2)
       if (value % d == 0)
         return false;

     return true;    
   }

Then enumerate prime numbers (2, 3, 5, 7, 11...):

   // Naive; sieve algorithm will be better off
   private static IEnumerable<int> Primes() {
     for (int i = 1; ; ++i)
       if (IsPrime(i))
         yield return i;
   }

Finally, query with a help of Linq:

   using System.Linq;

   ...

   int result = Primes().Skip(10000).First();

   Console.Write(result);

And you'll get

   104743 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 1
    Your loop `for (int d = 3; d <= n; ++d)` would be faster as `for (int d = 3; d <= n; d += 2)` You have already eliminated even numbers so you only need to check for odd divisors. – rossum Dec 08 '20 at 08:50
  • @rossum: thank you! I've overlooked this fact. – Dmitry Bychenko Dec 08 '20 at 09:00