c#中前1000个素数的和

本文关键字:中前 1000个 | 更新日期: 2023-09-27 18:13:09

我试图在c#中获得前1000个素数的总和,但我使用的代码非常慢,需要永远计算,到目前为止还没有返回一个有效的总和。

我是新来的,我希望你们中的任何一个人都能看看,帮助我使我的代码高效,也让我知道我做错了什么。如果我在论坛规则方面做错了什么,请告诉我。

提前感谢您的宝贵时间!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            long sumOfPrime=0;
            Console.WriteLine("Calculating Sum of Prime");
            for (int i = 1, primeCounter = 0; primeCounter <= 1000; ++i)
            {
                if (!IsPrime(i)) 
                { 
                    continue; 
                }
                else 
                { 
                    primeCounter = +1; 
                    sumOfPrime = +i; 
                }
            }
            Console.WriteLine(sumOfPrime);
        }
        static bool IsPrime(int number)
        {
            if (number == 1) 
            { 
                return false; 
            }
            if (number == 2) 
            { 
                return true; 
            }
            for (int i = 2; i <= Math.Ceiling(Math.Sqrt(number)); ++i)
            { 
                if (number % i == 0) 
                { 
                    return false; 
                } 
            }
            return true;
        }
    }
}       

c#中前1000个素数的和

您的错误在:

primeCounter = +1

每次重置计数器。我想你的意思是

primeCounter += 1

…它使它增加。或者更好:

primeCounter++

下面的代码返回3682913作为前1000个素数的和,并且在不到一秒的时间内完成。我不确定我是否遵循了IsPrime方法for循环中的逻辑。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Find1000Primes
{
    class Program
    {
        static void Main(string[] args)
        {
            int totalPrime = 0;
            int countPrime = 1000;
            int x = 0;  // counter for the primes
            int i = 0;  // each number that is checked starting with 0
            while (x < countPrime)
            {
                bool prime = IsPrime(i);
                if (prime)
                {
                    totalPrime = totalPrime + i;
                    x++;
                }
                i++;
            }
            Console.WriteLine(totalPrime.ToString());
            Console.ReadLine();
        }
        public static bool IsPrime(int number)
        {
            if ((number & 1) == 0)
            {
                if (number == 2)
                    return true;
                else
                    return false;
            }
            for (int i = 3; (i*i) <= number; i+=2)
            {
                if ((number % i) == 0)
                    return false;
            }
            return number != 1;
        }
    }
}