Sieve of Eratosthenes - Finding Primes Python

前端 未结 17 2508
旧巷少年郎
旧巷少年郎 2020-11-22 04:40

Just to clarify, this is not a homework problem :)

I wanted to find primes for a math application I am building & came across Sieve of Eratosthenes approach.

17条回答
  •  一整个雨季
    2020-11-22 05:18

    A simple speed hack: when you define the variable "primes," set the step to 2 to skip all even numbers automatically, and set the starting point to 1.

    Then you can further optimize by instead of for i in primes, use for i in primes[:round(len(primes) ** 0.5)]. That will dramatically increase performance. In addition, you can eliminate numbers ending with 5 to further increase speed.

提交回复
热议问题