首页 > 代码库 > Count Primes
Count Primes
Description:
Count the number of prime numbers less than a non-negative number, n.
//TLEclass Solution {private: bool isPrime(int n) { if (n <= 1) return false; for (int i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true; }public: int coutPrimes(int n) { int count = 0; for (int i = 1; i < n; i++) { if (isPrime(i)) count++; } return count; }};//筛数法class Solution2 {public: int countPrimes(int n) { if (n <= 1) return 0; bool* IsPrime = new bool[n]; for (int i = 2; i < n; i++) { IsPrime[i] = true; } for (int i = 2; i * i < n; i++) { if (!IsPrime[i]) continue; for (int j = i * i; j < n; j += i) { IsPrime[j] = false; } } int count = 0; for (int i = 2; i < n; i++) { if (IsPrime[i]) count++; } return count; }};
Count Primes
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。