Count the number of prime numbers less than a non-negative number, n.
Special thanks to @mithmatt for adding this problem and creating all test cases.
Let’s start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPrimefunction
would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could
we do better
# -*- coding:utf-8 -*- __author__ = 'jiuzhang' class Solution(object): def countPrimes(self, n): isPrime = [True] * max(n, 2) isPrime, isPrime = False, False x = 2 while x * x < n: if isPrime[x]: p = x * x while p < n: isPrime[p] = False p = x x = 1 return sum(isPrime)