本文介绍了寻找素数的程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到 0 和 long 变量之间的质数,但我无法得到任何输出.

I want to find the prime number between 0 and a long variable but I am not able to get any output.

程序是

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication16
{
    class Program
    {
        void prime_num(long num)
        {
            bool isPrime = true;
            for (int i = 0; i <= num; i++)
            {
                for (int j = 2; j <= num; j++)
                {
                    if (i != j && i % j == 0)
                    {
                        isPrime = false;
                        break;
                    }
                }
                if (isPrime)
                {
                    Console.WriteLine ( "Prime:" + i );
                }
                isPrime = true;
            }
        }

        static void Main(string[] args)
        {
            Program p = new Program();
            p.prime_num (999999999999999L);
            Console.ReadLine();
        }
    }
}

谁能帮我找出程序中可能存在的错误?

Can any one help me out and find what is the possible error in the program?

推荐答案

您可以像这样在一行(长)行中使用近乎最优 的试验分割筛来更快地完成此操作:

You can do this faster using a nearly optimal trial division sieve in one (long) line like this:

Enumerable.Range(0, Math.Floor(2.52*Math.Sqrt(num)/Math.Log(num))).Aggregate(
    Enumerable.Range(2, num-1).ToList(),
    (result, index) => {
        var bp = result[index]; var sqr = bp * bp;
        result.RemoveAll(i => i >= sqr && i % bp == 0);
        return result;
    }
);

这里使用的素数数量的近似公式是π(x)<1.26 x/ln(x).我们只需要通过不大于x = sqrt(num)的素数进行测试.

The approximation formula for number of primes used here is π(x) < 1.26 x / ln(x). We only need to test by primes not greater than x = sqrt(num).

请注意,埃拉托色尼筛分的运行时间复杂度比试除法(应该运行如果正确实现,对于更大的 num 值,速度会更快).

Note that the sieve of Eratosthenes has much better run time complexity than trial division (should run much faster for bigger num values, when properly implemented).

这篇关于寻找素数的程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 08:34