Python algorithm design - Eratosthenes sieve method

Python algorithm design source code: https://github.com/MakerChen66/Python3Algorithm

Copyright statement: Originality is not easy, this article prohibits plagiarism, reprinting, infringement must be investigated!

The Sieve of Eratosthenes

Eratosthenes sieve method is a very beautiful example algorithm.

Under the i7 CPU (single thread) processor, it can generate all prime numbers within 10^6 within 1s, so when this sieving algorithm is applied , the speed is amazing

and I used the most basic version (without splitting), just delete the even numbers in the array

Python algorithm implementation:


import numpy as np

def eratosthene(n):
    n = (n + 1) >> 1
    a = np.ones(n, dtype=np.int64)
    i, j = 1, 3

    while i < n:
        if a[i]:
            a[j * j >> 1::j] = 0
        i, j = i + 1, j + 2

    print(a.sum())

have a test:

eratosthene(1000000)

Note : np.ones(a, dtype=...) means to convert the current data a into an array of all 1s and the data type is dtype=..., a[i::j] means to get the array a from position i to The last position, and take one every j elements

Output result:
insert image description here
Indicates that there are 78498 prime numbers within 1000000

2. Source code download

Python algorithm design source code download:

3. Author Info

Author: Xiaohong's Fishing Daily, Goal: Make programming more interesting!

Original WeChat public account: " Xiaohong Xingkong Technology ", focusing on algorithms, crawlers, websites, game development, data analysis, natural language processing, AI, etc., looking forward to your attention, let us grow and code together!

Copyright Note: This article prohibits plagiarism and reprinting, and infringement must be investigated!

Guess you like

Origin blog.csdn.net/qq_44000141/article/details/122093830