gpt4 book ai didi

c# - 无法创建巨大的数组

转载 作者:可可西里 更新时间:2023-11-01 08:35:37 25 4
gpt4 key购买 nike

像许多其他程序员一样,我进入了primes ,和他们中的许多人一样,我喜欢的是挑战,所以我不是在寻找像阿特金做这件事比你哥们快这样的评论,而是一个解决方案 - 或者至少是一个提示 -我的问题。

我需要创建 数组(如大小> int.MaxValue)。所以我去了很多网页,找到了 gcAllowVeryLargeObjects Element一。我以为我得救了,将以下魔法添加到我的 App.config 中:

<configuration>
<runtime>
<gcAllowVeryLargeObjects enabled="true" />
</runtime>
</configuration>

但它没有起作用。这是我使用的代码:

void go(object sender, EventArgs eventArgs)
{
t.Stop();
ulong maxprime = 10;
Stopwatch stopwatch = new Stopwatch();
string s = String.Empty;
while (maxprime < ulong.MaxValue)
{
stopwatch.Restart();
richTextBox2.Text += Environment.NewLine + ("Max \t= " + maxprime.ToString("N0"));
try
{
richTextBox2.Text += Environment.NewLine + ("Count \t= " + GetAllPrimesLessThan(maxprime).Count);
richTextBox2.Text += Environment.NewLine + ("Time \t= " + stopwatch.Elapsed);
richTextBox2.Text += Environment.NewLine + ("--------------------------------");
maxprime *= 10;
richTextBox2.Refresh();
}
catch (Exception exception)
{
s = exception.Message + "; Allocation size: " + (maxprime + 1).ToString("N0");
break;
}

}
if (!string.IsNullOrEmpty(s))
{
richTextBox2.Text += Environment.NewLine + s;
}
richTextBox2.Text += Environment.NewLine + ("Done.");
}

private static List<ulong> GetAllPrimesLessThan(ulong maxPrime)
{
var primes = new List<ulong>() { 2 };
var maxSquareRoot = Math.Sqrt(maxPrime);
var eliminated = new bool[maxPrime + 1];

for (ulong i = 3; i <= maxPrime; i += 2)
{
if (!eliminated[i])
{
primes.Add(i);
if (i < maxSquareRoot)
{
for (ulong j = i * i; j <= maxPrime; j += 2 * i)
{
eliminated[j] = true;
}
}
}
}
return primes;
}

哪个输出这个:

[...]
Max = 1 000 000 000
Count = 50847534
Time = 00:00:15.3355367
--------------------------------
Max = 10 000 000 000
Array dimensions exceeded supported range.; Allocation size: 10 000 000 001
Done.

我怎样才能摆脱这个错误?


仅供引用:我有

  • 16GB 内存;
  • 32GB 内存映射(/分页?)在 SSD 上;
  • 启用 64 位

最佳答案

来自您的链接:

Using this element in your application configuration file enables arrays that are larger than 2 GB in size, but does not change other limits on object size or array size:

The maximum index in any single dimension is 2,147,483,591 (0x7FFFFFC7) for byte arrays and arrays of single-byte structures, and 2,146,435,071 (0X7FEFFFFF) for other types.

另见 What is the maximum length of an array in .NET on 64-bit Windows :

An array could theoretically have at most 2,147,483,647 elements, since it uses an int for indexing.

关于c# - 无法创建巨大的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30895549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com