📜  Eratosthenes筛

📅  最后修改于: 2021-04-26 19:30:03             🧑  作者: Mango

给定数字n,请打印所有小于或等于n的素数。还假定n是一个小数。

例子:

Eratosthenes的筛网是在n小于1000万左右时查找所有小于n的素数的最有效方法之一(请参阅Wiki)。

以下是通过Eratosthene方法找到所有小于或等于给定整数n的素数的算法:
当算法终止时,列表中所有未标记的数字均为质数。

举例说明:
让我们以n = 50时为例。因此,我们需要打印所有小于或等于50的质数。
我们创建一个从2到50的所有数字的列表。

筛1

根据该算法,我们将标记所有可被2整除且大于或等于其平方的数字。

筛2

现在,我们移至下一个未标记的数字3,并标记所有3的倍数且大于或等于其平方的数字。

癫痫筛网3

我们移到下一个未标记的数字5并标记5的所有倍数,并且大于或等于它的平方。

筛网4

我们继续进行此过程,最终表将如下所示:

筛5

因此素数是未标记的素数:2、3、5、7、11、13、17、19、23、29、31、37、41、43、47。
感谢Krishan Kumar提供了以上解释。
执行:
以下是上述算法的实现。在以下实现中,大小为n的布尔数组arr []用于标记质数的倍数。

C++
// C++ program to print all primes
// smaller than or equal to
// n using Sieve of Eratosthenes
#include 
using namespace std;
 
void SieveOfEratosthenes(int n)
{
    // Create a boolean array
    // "prime[0..n]" and initialize
    // all entries it as true.
    // A value in prime[i] will
    // finally be false if i is
    // Not a prime, else true.
    bool prime[n + 1];
    memset(prime, true, sizeof(prime));
 
    for (int p = 2; p * p <= n; p++)
    {
        // If prime[p] is not changed,
        // then it is a prime
        if (prime[p] == true)
        {
            // Update all multiples
            // of p greater than or
            // equal to the square of it
            // numbers which are multiple
            // of p and are less than p^2
            // are already been marked.
            for (int i = p * p; i <= n; i += p)
                prime[i] = false;
        }
    }
 
    // Print all prime numbers
    for (int p = 2; p <= n; p++)
        if (prime[p])
            cout << p << " ";
}
 
// Driver Code
int main()
{
    int n = 30;
    cout << "Following are the prime numbers smaller "
         << " than or equal to " << n << endl;
    SieveOfEratosthenes(n);
    return 0;
}


Java
// Java program to print all
// primes smaller than or equal to
// n using Sieve of Eratosthenes
 
class SieveOfEratosthenes {
    void sieveOfEratosthenes(int n)
    {
        // Create a boolean array
        // "prime[0..n]" and
        // initialize all entries
        // it as true. A value in
        // prime[i] will finally be
        // false if i is Not a
        // prime, else true.
        boolean prime[] = new boolean[n + 1];
        for (int i = 0; i <= n; i++)
            prime[i] = true;
 
        for (int p = 2; p * p <= n; p++)
        {
            // If prime[p] is not changed, then it is a
            // prime
            if (prime[p] == true)
            {
                // Update all multiples of p
                for (int i = p * p; i <= n; i += p)
                    prime[i] = false;
            }
        }
 
        // Print all prime numbers
        for (int i = 2; i <= n; i++)
        {
            if (prime[i] == true)
                System.out.print(i + " ");
        }
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int n = 30;
        System.out.print(
            "Following are the prime numbers ");
        System.out.println("smaller than or equal to " + n);
        SieveOfEratosthenes g = new SieveOfEratosthenes();
        g.sieveOfEratosthenes(n);
    }
}
 
// This code has been contributed by Amit Khandelwal.


Python
# Python program to print all
# primes smaller than or equal to
# n using Sieve of Eratosthenes
 
 
def SieveOfEratosthenes(n):
 
    # Create a boolean array
    # "prime[0..n]" and initialize
    #  all entries it as true.
    # A value in prime[i] will
    # finally be false if i is
    # Not a prime, else true.
    prime = [True for i in range(n+1)]
    p = 2
    while (p * p <= n):
 
        # If prime[p] is not
        # changed, then it is a prime
        if (prime[p] == True):
 
            # Update all multiples of p
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1
 
    # Print all prime numbers
    for p in range(2, n+1):
        if prime[p]:
            print p,
 
 
# Driver code
if __name__ == '__main__':
    n = 30
    print "Following are the prime numbers smaller",
    print "than or equal to", n
    SieveOfEratosthenes(n)


C#
// C# program to print all primes
// smaller than or equal to n
// using Sieve of Eratosthenes
using System;
 
namespace prime {
public class GFG {
 
    public static void SieveOfEratosthenes(int n)
    {
 
        // Create a boolean array
        // "prime[0..n]" and
        // initialize all entries
        // it as true. A value in
        // prime[i] will finally be
        // false if i is Not a
        // prime, else true.
 
        bool[] prime = new bool[n + 1];
 
        for (int i = 0; i < n; i++)
            prime[i] = true;
 
        for (int p = 2; p * p <= n; p++)
        {
            // If prime[p] is not changed,
            // then it is a prime
            if (prime[p] == true)
            {
                // Update all multiples of p
                for (int i = p * p; i <= n; i += p)
                    prime[i] = false;
            }
        }
 
        // Print all prime numbers
        for (int i = 2; i <= n; i++)
        {
            if (prime[i] == true)
                Console.Write(i + " ");
        }
    }
 
    // Driver Code
    public static void Main()
    {
        int n = 30;
        Console.WriteLine(
            "Following are the prime numbers");
        Console.WriteLine("smaller than or equal to " + n);
        SieveOfEratosthenes(n);
    }
}
}
 
// This code is contributed by Sam007.


PHP


Javascript


输出
Following are the prime numbers smaller  than or equal to 30
2 3 5 7 11 13 17 19 23 29 

时间复杂度: O(n * log(log(n)))

您可能还会喜欢看:

  • Eratosthenes筛的时间复杂度如何为n * log(log(n))?
  • 分段筛。
  • 时间复杂度为0(n)的Eratosthenes筛