1324. The number of prime numbers
Chinese
English
Count the number of prime numbers less than the non-negative number n.
Sample
Sample 1
输入: n = 2
输出: 0
Sample 2
输入: n = 4
输出: 2
解析:2, 3 是素数
class Solution: '' ' General idea: 1. Initialization list [ 0 , 0 , 0 , 0 , 0 ], outer loop n, inner loop range (i * 2, n, i ), set the value to 1, 2 . In the end [ 0 , 1 , 2 , 3 ] all of these default to 0, so you need to subtract the two values of 0, 1 that are not prime numbers, which is the result. The ones that are not prime numbers are assigned a value of 1. '' ' def countPrimes (self, n): l = [ 0 ] * n ## At the beginning, set the prime number to 1 for j in range ( 2 , n): if l [j]! = 1: for z in range (j * 2 , n, j): # It can't be counted by itself, such as 5,7, can only take 10,14 as non-prime numbers, increasing by j. Until n. l [z] = 1 return l.count ( 0 ) -2