【发布时间】:2014-09-06 16:13:31
【问题描述】:
我已经编写了这段代码来查找素数,它运行良好,但是计算速度非常慢.....我做错了吗?我知道我可能真的以错误的方式做这件事,但请帮助我!非常感谢!
using System;
using System.Collections.Generic;
namespace Primenumbers
{
class MainClass
{
public static void Main (string[] args)
{
List<int> NoPrime = new List<int>();
for(int x = 2; x < 10000;x++)
{
for(int y = x * 2;y < 10000;y = y + x)
{
if(!NoPrime.Contains(y))
{
NoPrime.Add(y);
}
}
}
for(int z = 2; z < 10000;z++)
{
if(!NoPrime.Contains(z))
{
Console.WriteLine(z);
}
}
}
}
}
编辑: 这是新代码,我将“List”更改为“HashSet”并添加了一个计数器来获取所有素数的总和。非常感谢所有评论/回答的人,你们太棒了!
using System;
using System.Collections.Generic;
class MainClass
{
public static void Main (string[] args)
{
HashSet<int> NoPrime = new HashSet<int>();
long count = 0;
int n = 2000000;
for(int x = 2; x < n;x++)
{
for(int y = x * 2;y < n;y = y + x)
{
if(!NoPrime.Contains(y))
{
NoPrime.Add(y);
}
}
for(int z = 2; z < n;z++)
{
if(!NoPrime.Contains(z))
{
Console.WriteLine(z);
count = count + z;
}
}
Console.WriteLine("Sum is: " + count);
}
}
【问题讨论】:
-
使用 HashSet 而非 List..
-
包含进行线性搜索。我建议使用数组。使用的内存更多,但速度更快。
-
这个问题可能更适合codereview.stackexchange.com
-
@Ondra:不,不是。 List 使用数组进行内部存储,没错,但在素数/非素数方面它是稀疏的。该数组是密集的,这使得查找特定元素变得简单而快速。
-
@ondra:我不是说使用 array.contains。我的意思是在索引处检查 0 或 1。例如 a (4) = 0 表示 4 不是素数。 a (5) = 1 表示 5 是素数。