相关疑难解决方法(0)

最优雅的方式来生成素数

实现此功能的最佳方式是什么:

ArrayList generatePrimes(int n)
Run Code Online (Sandbox Code Playgroud)

此函数生成第一个n素数(编辑:where n>1),因此generatePrimes(5)将返回ArrayListwith {2, 3, 5, 7, 11}.(我在C#中这样做,但我很高兴Java实现 - 或任何其他类似的语言(所以不是Haskell)).

我知道怎么写这个函数,但是当我昨晚做到这一点时,它并没有像我希望的那样结束.这是我想出的:

ArrayList generatePrimes(int toGenerate)
{
    ArrayList primes = new ArrayList();
    primes.Add(2);
    primes.Add(3);
    while (primes.Count < toGenerate)
    {
        int nextPrime = (int)(primes[primes.Count - 1]) + 2;
        while (true)
        {
            bool isPrime = true;
            foreach (int n in primes)
            {
                if (nextPrime % n == 0)
                {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime)
            {
                break;
            }
            else
            {
                nextPrime …
Run Code Online (Sandbox Code Playgroud)

c# java algorithm primes

81
推荐指数
7
解决办法
6万
查看次数

无法创建庞大的数组

像许多其他程序员一样,我进入了素数,而且他们中的很多人,我喜欢的是挑战,所以我不是在寻找评论,比如阿特金比你这么做得快,但只是一个解决方案 - 或者至少是一个暗示 - 对我的问题.

我需要创建数组(如size> int.MaxValue).所以我去了很多网页,发现gcAllowVeryLargeObjects元素一个.我以为我得救了,给我加上以下魔法App.config:

<configuration>
  <runtime>
    <gcAllowVeryLargeObjects enabled="true" />
  </runtime>
</configuration>
Run Code Online (Sandbox Code Playgroud)

但它没有奏效.这是我使用的代码:

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= …
Run Code Online (Sandbox Code Playgroud)

c# arrays

11
推荐指数
2
解决办法
2万
查看次数

标签 统计

c# ×2

algorithm ×1

arrays ×1

java ×1

primes ×1