Blue Bridge Cup - Prime Number - Esperanto Sieve (Python)

1. Topic

2. Code

import os
import sys

# 请在此输入您的代码
def countPrimes(n):
  primes=[1]*n
  count=0
  li=[]
  for i in range(2,n):
    if primes[i]:
        count+=1
        li.append(i)
        for j in range(i*i,n,i):
          primes[j]=0
  return count,li
  
n=int(input())
a,b=countPrimes(n)
print(*b)
print(a)

3. El Sieve

        Sieve of Eratosthenes (Sieve of Eratosthenes) is an ancient prime number sieve method, which can be used to quickly find all prime numbers less than or equal to a certain positive integer N. Its name comes from the ancient Greek scholar Eratosthenes.

        The basic idea of ​​the algorithm is: first use the smallest prime number 2 to sieve, mark the multiples of 2 as composite numbers, and then use the next prime number to sieve, repeat this process until all numbers less than or equal to N are sieved once. The last unmarked number is a prime number.

        The specific implementation process can use a Boolean array of length N to indicate whether each number is a prime number. Initially, all elements are marked as prime numbers, and then each prime number p is enumerated from 2, and all multiples of p are marked as Composite numbers (i.e. marked false in the boolean array) until p*p>N. Finally, all elements not marked as composite numbers are prime numbers.

        The Essieve method is a simple and efficient algorithm with a time complexity of O(NloglogN) and a space complexity of O(N). But when dealing with large-scale data, its space complexity will become a bottleneck, because a large amount of space needs to be opened up to store Boolean arrays. At this time, other prime number sieve methods can be considered, such as Euler sieve, linear sieve, etc.

4. Code explanation

        Define the function countPrimes(n), the function of the function is to calculate the number of prime numbers less than n, and return these prime numbers. The specific implementation idea inside the function is as follows:

  1. First, we create a list primes of length n, the initial value is all 1, which means that all numbers are prime numbers.

  2. Create a counter count representing the number of prime numbers less than n.

  3. Create a list li to store all prime numbers less than n.

  4. Traverse every number i from 2 to n-1.

  5. If primes[i] is equal to 1, it means that i is a prime number, add 1 to count, and add i to the li list.

  6. Next, traverse every multiple j of i starting from i^2 to n-1. Since all multiples of i from 2 to i-1 are marked, we start with i^2.

  7. Mark primes[j] as 0, indicating that j is not a prime number.

  8. Finally, count and li are returned, respectively representing the number of prime numbers less than n and all prime numbers less than n.

Guess you like

Origin blog.csdn.net/m0_62428181/article/details/129883086
Recommended