Topic Overview:
Description:
Count the number of prime numbers less than a non-negative number, n.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Problem Solving Ideas:
The idea is divided into the following steps:
- First, an array of length n is set to Prime, which is used from 0 to n-1.
- Set prime[0] and prime[1] to false, since 0 and 1 are not prime numbers.
- Next, for the critical step, set the not prime number to false for the integer less than n.
- If a positive integer can be expressed as a product of two numbers (except 1), then the number is not a prime, so we need to find two numbers, and if the product of these two numbers is less than n, the result of multiplying is not a prime.
- First, the first multiplier I, we need to take I as a prime number, because the non-prime can certainly be expressed by prime numbers, the calculation of the product of non-prime is caused by unnecessary additional computation. I only need to consider the value of 2 to sqrt (n) +1, because when the I>SQRT (n), I is larger than the number of itself, the result is necessarily greater than n, and if I multiplied by its own small number, it is redundant calculation, because this part of the calculation has been calculated by I in the previous value.
- Next is the second multiplier J, J is a multiplier, the purpose is to remove the multiples of the number of primes in the N range.
- The last step is to count the number of true digits remaining in the prime, that is, the number of primes
Code:
classsolution (object):defcountprimes (self, n):""": Type N:int:rtype:int""" ifN <=2: return0 Prime= [true]*N prime[0],prime[1] =False,false forIinchRange (2,int (n**0.5) +1): ifPrime[i]: prime[i*I:N:I] = [False]*len (prime[i*i:n:i])returnSUM (Prime)
Leetcode 204. Count Primes