tags:

views:

143

answers:

3

Hello, I am new to C# and I am practicing by trying to solve this easy C# problem. This application will receive an "n" number. After receiving this number, the program has to show the n prime of the list of primes. For example, if the user enters "3", the program is supposed to display "5", because 5 is the third prime starting at 2. I koow that something is wrong with my code but I dont know where is the problem and how I can fix it. Can you please tell me? Thank you :P

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Determinar el n-esimo primo.");
            long n = Convert.ToInt64(Console.ReadLine()); // N lugar de primos
            long[] array = new long[n];
            long c=0;
            while (c >= 2) 
            { 
                if(siprimo(c++) == true)
                    for (long i = 0; i < n; i++)
                    {
                        array[i] = c;

                    }

            }


            Console.WriteLine(array[n - 1]);
            Console.ReadLine();


        }
        static private bool siprimo(long x)
        {
            bool sp = true;
            for (long k = 2; k <= x / 2; k++)
                if (x % k == 0)
                    sp = false;
            return sp;
        }

    }
}
+1  A: 

This looks like homework, and I'm not going to do your homework for you. But I will tell you that the problem is VERY easy to find if you simply STEP THROUGH your program (use F10 in Visual Studio).

Hint: When does c get incremented?

Charles
+1  A: 

Some other questions to ask yourself:

  • when a prime number is found (siprime), where does the value get stored?
  • how many times are you looping through the while (c >= 2) code block?
Kirk Broadhurst
Good point. Yikes!
Charles
A: 

More like:

int GetAnswer(int nprime) {
   if (nprime == 1) return 2;
   if (nprime == 2) return 3;

   int j;
   int n = 2; 
   int i = 5;

   while (n < nprime)  {

     int isprime = 1;
     double r = Math.Sqrt(i);

     for(j = 3; j <= r;  j+=2)
        if((i%j) == 0) {
           isprime = 0;
           break;
        } 


     n+=isprime; 
     i+=2;
   }
   return i;
 }

In your program you made some mistakes like:

long c=0;
while (c >= 2) 

C is never greater than 2 so the code never gets executed.

Mack