【问题标题】:Finding the nth prime in the set of prime numbers.在素数集合中找到第 n 个素数。
【发布时间】:2010-03-24 04:59:39
【问题描述】:

此应用程序将收到一个数字“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;
        }
    }
}

【问题讨论】:

  • 顺便说一句,请返回并“接受”您对第一个问题的首选答案。如果您这样做,人们将更有可能回答您随后提出的问题。 :)

标签: c# primes


【解决方案1】:

这看起来像是作业,我不会为你做作业。但是我会告诉你,如果你只是简单地通过你的程序(在 Visual Studio 中使用 F10),这个问题很容易找到。

提示:c 什么时候递增?

【讨论】:

    【解决方案2】:

    还有一些问题要问自己:

    • 找到质数 (siprime) 时,该值将存储在哪里?
    • 您循环了多少次 while (c &gt;= 2) 代码块?

    【讨论】:

      【解决方案3】:

      更像:

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

      在您的程序中,您犯了一些错误,例如:

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

      C 永远不会大于 2,因此代码永远不会被执行。

      【讨论】:

        猜你喜欢
        • 2013-01-22
        • 1970-01-01
        • 2017-05-06
        • 2016-02-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多