Generate Prime Numbers via Eratosthene#39;s Sieve C#(通过Eratosthene的筛子C#生成素数)
本文介绍了通过Eratosthene的筛子C#生成素数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试解决Project Euler的问题3,Foundhere.我想通过使用Eratosthene筛子生成素数列表来解决它(Foundhere.我远未完成问题,但我遇到了一个小问题... 下面是我为此编写的代码。然而,当我运行这段代码时,它会停止我的计算机,并输出一个2,然后再延迟一些。它显然在运行,但似乎做得不对。在它输出列表之前,它应该让我知道(只是检查是否在输出之前挂断)它已经完成了列表的分配...
如果您不确定发生了什么,您能给我一些指导,让我深入了解代码并调试它的不同行吗?我在不同的区域尝试过Console.WriteLine,但它似乎对代码没有响应。
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
static void Main(string[] args)
{
long maxNum = 100;
double maxSqrt = Math.Floor(Math.Sqrt(maxNum));
long basePrime;
// Make a list from 2 to maxNum
List<long> numberList = new List<long>();
List<long> sievedList = new List<long>();
for (long i = 2; i <= maxNum; i++) numberList.Add(i);
// Evaluate the first number of the list, if it is < maxSqrt skip it, create a list of multiples and Except them from numberList, else, numberList is completely Prime Factors
foreach (long number in numberList.Skip(1))
{
basePrime = numberList[0];
Console.WriteLine(basePrime);
while (number < maxSqrt)
{
if (number % basePrime == 0)
{
sievedList.Add(number);
}
numberList = numberList.Except(sievedList).ToList();
sievedList.Clear();
}
}
Console.WriteLine("Finished Allocating Primes");
numberList.ForEach(Console.WriteLine);
}
}
推荐答案
对于您的紧急问题,请将while更改为if。
但是,您的代码还存在其他问题。
- 您的
numberedList只是用for循环填充的从2到maxNum的整数列表。然后,您将遍历列表。只需使用for循环中的计数器即可。为了记录哪些数字是质数,BitArray(Int32, Boolean)很有效。 - 这也允许摆脱昂贵的LINQ扩展。当您找到一个非素数时,只需更改它在位数组中的索引即可。找到质数后,将其添加到列表中;
这篇关于通过Eratosthene的筛子C#生成素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:通过Eratosthene的筛子C#生成素数
猜你喜欢
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 输入按键事件处理程序 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
