Search for the nth number in a set of primes.

This app will get the number "n". After receiving this number, the program should show the nth number in the list of primes. For example, if the user enters “3,” the program should display “5,” because 5 is the third prime, starting with 2. I know that something is wrong with my code, but I don’t know where the problem is and how I can fix it.

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
source share
3 answers

More likely:

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;
 }

You made some errors in your program, for example:

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

C never exceeds 2, so the code will never be executed.

0
source

, . , , STEP THROUGH ( F10 Visual Studio).

: c ?

+2

Some other questions to ask yourself:

  • when a prime number (siprime) is found, where is the value stored?
  • how many times do you execute the code loop while (c >= 2)?
+2
source

Source: https://habr.com/ru/post/1738909/


All Articles