Count the number of prime numbers less than a non-negative number, n.
Example:
Input:10output:4explanation:there is 4 prime numbers less than, they is 2, 3, 5, 7.
Counts the number of all prime numbers that are less than nonnegative integer n .
Example:
Input: 10 Output: 4 Explanation: There are 4 of prime numbers less than 10, they are 2, 3, 5, 7.
424ms
1 classSolution {2Func CountPrimes (_ N:int)Int {3 ifN <2{return 0}4 //Screening Method5 varCount =06 //to create an array with default values7 varFlag = Array (repeating:false, Count:n)8 varVal:int =Int ()9 forIinch 2.. <NTen { One ifFlag[i] = =false A { -Count + =1 - varJ:int =1 theval = j*I - while(true) - { -J + =1 +val = j*I - if(Val <N) + { AFlag[val] =true at } - Else - { - Break - } - } in } - } to returnCount + } -}
84ms
1 classSolution {2Func CountPrimes (_ N:int)Int {3Guard n >2 Else{return 0 }4 varSieve = [Bool] (repeating:true, Count:n)5 varCount = N/26 vari =37 8 whileI * I <N {9 ifSieve[i] {Ten varj = i *I One A whileJ <N { - ifSieve[j] { -Count-=1 theSIEVE[J] =false - } -J + =2*I - } + } -i + =2 + } A at returnCount - } -}
112ms
1 classSolution {2Func CountPrimes (_ N:int)Int {3Guard N >=3 Else{return 0 }4 varprimes = [Bool] (repeating:true, Count:n)5 varCount = n/26 vari =37 whileI <=Int (Double (n). SquareRoot ()) {8 ifPrimes[i] {9 varj =ITen whileI*j <N { One ifprimes[i*J] { ACount-=1 -PRIMES[I*J] =false - } theJ + =2 - } - } -i + =2 + } - returnCount + } A}
204. Count Prime Numbers | Count Primes