Description: Count the number of prime numbers less than a non-negative number, n. Code c++ C++ class Solution { public: int countPrimes(int n) { if (n <= 2) return 0; bool * isPrimer = new bool[n]; for (int i = 0; i < n; i++) isPrimer[i] = true; for (int i = 2; i * i < n; i++) { if (isPrimer[i]) for (int j = i ; j * i < n; j ++) isPrimer[j * i] = false; } int res = 0; for (int i = 2; i < n; i++) if (isPrimer[i]) res++; delete[] isPrimer; return res; } }; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 for (int i = 0; i < n; i++) isPrimer[i] = true; for (int i = 2; i * i < n; i++) { if (isPrimer[i]) isPrimer[j * i] = false; if (isPrimer[i]) res++; java Java public class Solution { public int countPrimes(int n) { if (n <= 2) return 0; boolean[] isPrimer = new boolean[n]; for(int i=2;i
Read full article from leetcode Count Primes - 细语呢喃
No comments:
Post a Comment