204. 計數質數 | Count Primes
阿新 • • 發佈:2018-10-05
class The val true fun ati less eat xpl
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
統計所有小於非負整數 n 的質數的數量。
示例:
輸入: 10 輸出: 4 解釋: 小於 10 的質數一共有 4 個, 它們是 2, 3, 5, 7 。
424ms
1 class Solution { 2 func countPrimes(_ n: Int) -> Int {3 if n < 2 {return 0} 4 //篩選法 5 var count = 0 6 //創建具有默認值的數組 7 var flag = Array(repeating: false, count: n) 8 var val:Int = Int() 9 for i in 2..<n 10 { 11 if flag[i] == false 12 { 13 count += 114 var j:Int = 1 15 val = j*i 16 while(true) 17 { 18 j += 1 19 val = j*i 20 if(val < n) 21 { 22 flag[val] = true 23 }24 else 25 { 26 break 27 } 28 } 29 } 30 } 31 return count 32 } 33 }
84ms
1 class Solution { 2 func countPrimes(_ n: Int) -> Int { 3 guard n > 2 else { return 0 } 4 var sieve = [Bool](repeating: true, count: n) 5 var count = n / 2 6 var i = 3 7 8 while i * i < n { 9 if sieve[i] { 10 var j = i * i 11 12 while j < n { 13 if sieve[j] { 14 count -= 1 15 sieve[j] = false 16 } 17 j += 2 * i 18 } 19 } 20 i += 2 21 } 22 23 return count 24 } 25 }
112ms
1 class Solution { 2 func countPrimes(_ n: Int) -> Int { 3 guard n >= 3 else { return 0 } 4 var primes = [Bool](repeating: true, count: n) 5 var count = n/2 6 var i = 3 7 while i <= Int(Double(n).squareRoot()) { 8 if primes[i] { 9 var j = i 10 while i*j < n { 11 if primes[i*j] { 12 count -= 1 13 primes[i*j] = false 14 } 15 j += 2 16 } 17 } 18 i += 2 19 } 20 return count 21 } 22 }
204. 計數質數 | Count Primes