10001 Prime - 项目欧拉

时间:2017-03-26 05:52:24

标签: c# math

所以我正在做第7个项目欧拉问题,而且我不确定为什么这个代码不起作用,好像这么小的数字,我已经测试了1 -10很好,但在10001没有返回正确答案 - 返回104745。

是的,我知道它效率低下。

private void eulerSeven(int num)
    {
        // Start the Prime count at 3, with 2 already counted. 
        int primecount = 1, counter = 3;

        //While num of primes counted < the nth prime
        while (primecount < num)
        {                
            bool isPrime = true;
            //check every number from 2 -> the current number we're checking
            for (int i = 2; i < counter; i++)
            {
                if (counter%i == 0)
                {
                    //if divisible, not a prime
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) //If is a prime, increment counter
            {   primecount++; }
            // Go to next number (only checking odds)
            counter += 2;
        }

        //output nth prime
       Console.WriteLine(counter);
    }

1 个答案:

答案 0 :(得分:0)

如@lanorkin所述,问题是:

  

应为counter - 2

但是,我想建议看一下https://codereview.stackexchange.com/questions/124644/project-euler-7-10001st-prime,所以这段代码应该做同样的事情,但非常快(我机器上5ms):

static void Main(string[] args)
{
    var stopwatch = Stopwatch.StartNew();
    Console.WriteLine(CalculateEulerSeven(10001)); // should be 104745
    stopwatch.Stop();

    Console.WriteLine("Time to calculate in milliseconds : {0}", stopwatch.ElapsedMilliseconds);
    Console.ReadKey();
}

private static int CalculateEulerSeven(int num)
{
    int primecount = 1, counter = 3;

    while (primecount < num)
    {
        bool isPrime = IsPrime(counter);

        if (isPrime) primecount++;
        counter += 2;
    }

    return counter;
}

static bool IsPrime(int value)
{
    if (value < 2) { return false; }
    if (value % 2 == 0) { return value == 2; }
    if (value % 3 == 0) { return value == 3; }
    if (value % 5 == 0) { return value == 5; }
    if (value == 7) { return true; }

    for (int divisor = 7; divisor * divisor <= value; divisor += 30)
    {
        if (value % divisor == 0) { return false; }
        if (value % (divisor + 4) == 0) { return false; }
        if (value % (divisor + 6) == 0) { return false; }
        if (value % (divisor + 10) == 0) { return false; }
        if (value % (divisor + 12) == 0) { return false; }
        if (value % (divisor + 16) == 0) { return false; }
        if (value % (divisor + 22) == 0) { return false; }
        if (value % (divisor + 24) == 0) { return false; }
    }

    return true;
}