找出素数集中的第n个素数. [英] Finding the nth prime in the set of prime numbers.

查看:60
本文介绍了找出素数集中的第n个素数.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

更多类似:

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 永远不会大于 2,因此代码永远不会被执行.

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

这篇关于找出素数集中的第n个素数.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆