为N = 2000000提供正确答案,但不通过测试用例

时间:2019-01-01 15:10:49

标签: c#

查找所有不大于N的质数之和。例如,如果用户输入5,则质数为2,3,5,其质数为10。它没有通过4个测试用例,其中两个超出时间限制。我已经尝试了几个测试用例,并且我的代码在它们上运行良好。这是我的代码。

public static long sieve_of_eratosthenes(long n)
{
    if (n == 1)
    {
        // If the user input 1.
        return (0);
    }
    else
    {
        long sum = 0;
        bool[] array = new bool[n + 1];
        for (long i = 2; i <= n; i++)
        {
            // Setting all values to true.
            array[i] = true;                        
        }
        // Eliminating the composite numbers.
        for (long j = 2; j < Math.Sqrt(n); j++)            
        {
            if (array[j])
            {
                long multiple = 1;
                for (long k = (j * j); k <= n; k = (j * j) + (j * (multiple++)))
                {
                    array[k] = false;
                }
            }
        }
        //Now we have the prime numbers. We just have to add them.
        for (int z = 2; z <= n; z++)
        {
            if (array[z])
            {
                sum = sum + z;
            }
        }
        return (sum);
    }
}

static void Main(string[] args)
{
    int noofcases = int.Parse(Console.ReadLine());
    for( int i = 0; i < noofcases; i ++)
    {
        long entry = long.Parse(Console.ReadLine());
        Console.WriteLine(sieve_of_eratosthenes(entry));
    }
}

1 个答案:

答案 0 :(得分:2)

检查以下代码。我写了可以改进的简单逻辑

public static class Int32Extension
{
    public static bool IsPrime(this int number)
    {
        if (number <= 1) return false;
        if (number == 2) return true;
        if (number % 2 == 0) return false;

        var boundary = (int)Math.Floor(Math.Sqrt(number));

        for (int i = 3; i <= boundary; i += 2)
            if (number % i == 0)
                return false;

        return true;
    }
}

然后

static void Main(string[] args)
{
    int input = 5;
    int sum = 0;

    for (int i = 0; i < input;)
    {
        if (!(++i).IsPrime())
            continue;

        sum += i;
    }

    Console.WriteLine(sum);
}

不使用扩展方法

public static bool IsPrime(int number)
{
    if (number <= 1) return false;
    if (number == 2) return true;
    if (number % 2 == 0) return false;

    var boundary = (int)Math.Floor(Math.Sqrt(number));

    for (int i = 3; i <= boundary; i += 2)
        if (number % i == 0)
            return false;

    return true;
}

static void Main(string[] args)
{
    int input = 5;
    int sum = 0;

    for (int i = 0; i < input;)
    {
        if (!IsPrime(++i))
            continue;

        sum += i;
    }

    Console.WriteLine(sum);
}

.Net小提琴链接:https://dotnetfiddle.net/rEBY9r

编辑:IsPrime测试使用Primality Test With Pseudocode