问题
This application will receive a number "n". After receiving this number, the program has to show the nth prime in 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 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:
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.
回答2:
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?
回答3:
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?
来源:https://stackoverflow.com/questions/2505433/finding-the-nth-prime-in-the-set-of-prime-numbers