Most efficient code for the first 10000 prime numbers?

前端 未结 30 1492
日久生厌
日久生厌 2020-11-29 19:09

I want to print the first 10000 prime numbers. Can anyone give me the most efficient code for this? Clarifications:

  1. It does not matter if your code is ineffici
30条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 19:37

    Using Sieve of Eratosthenes, computation is quite faster compare to "known-wide" prime numbers algorithm.

    By using pseudocode from it's wiki (https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes), I be able to have the solution on C#.

    /// Get non-negative prime numbers until n using Sieve of Eratosthenes.
    public int[] GetPrimes(int n) {
        if (n <= 1) {
            return new int[] { };
        }
    
        var mark = new bool[n];
        for(var i = 2; i < n; i++) {
            mark[i] = true;
        }
    
        for (var i = 2; i < Math.Sqrt(n); i++) {
            if (mark[i]) {
                for (var j = (i * i); j < n; j += i) {
                    mark[j] = false;
                }
            }
        }
    
        var primes = new List();
        for(var i = 3; i < n; i++) {
            if (mark[i]) {
                primes.Add(i);
            }
        }
    
        return primes.ToArray();
    }
    

    GetPrimes(100000000) takes 2s and 330ms.

    NOTE: Value might vary depend on Hardware Specifications.

提交回复
热议问题