Skip to main content
 首页 » 编程设计

c#之在素数集中寻找第 n 个素数。

2024年02月24日20arxive

此应用程序将收到一个数字“n”。收到这个数字后,程序必须显示素数列表中的第 n 个素数。例如,如果用户输入“3”,程序应该显示“5”,因为 5 是从 2 开始的第三个质数。我知道我的代码有问题,但我不知道问题出在哪里以及我该如何修复它。

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

请您参考如下方法:

这看起来像是家庭作业,我不会为您做家庭作业。但我会告诉您,如果您只是单步执行程序(在 Visual Studio 中使用 F10),问题就很容易找到。

提示:c 何时递增?