1, 题目
统计所有小于非负整数 n 的质数的数量。
示例:
输入: 10输出: 4解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
2, 算法
object Solution {def countPrimes(n: Int): Int = {if (n < 2) {return 0}val arr = Array.fill(n)(1)arr(0) = 0arr(1) = 0for (i <- 2 to scala.math.sqrt(n).toInt) {var j = 2 * iwhile (j < n) {arr(j) = 0j += i}}arr.sum}}
class Solution:def countPrimes(self, n: int) -> int:if n < 2:return 0result = [1] * nresult[0] = 0result[1] = 0import mathimport functoolsfor i in range(2, int(math.sqrt(n)) + 1):j = 2 * iwhile j < n:result[j] = 0j += ireturn functools.reduce(lambda x, y: x + y, result)
