[leetcode] 204. Count Primes @ python
阿新 • • 發佈:2019-01-08
原題
https://leetcode.com/problems/count-primes/
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
解法
假設0, 1, … n-1是質數, 初始化列表primes, 已知0和1不是質數, 設為0, 從最小的質數2開始, 2的所有倍數(2倍以上)都不是質數, 設為0. 最後統計質數列表的和.
程式碼:
class Solution:
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
# base case
if n < 3: return 0
# suppose 0, 1, ...n-1 are primes
primes = [1]*n
# 0 and 1 are not primes
primes[0] = primes[1] = 0
for i in range(2, n):
if primes[i] == True:
for j in range(2, (n-1)//i+1):
primes[i*j] = 0
return sum(primes)