204. Count Primes

来源:互联网 发布:程序员平均年龄 编辑:程序博客网 时间:2024/05/22 04:58

Description:

Count the number of prime numbers less than a non-negative number, n.

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Hint:

  1. Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity ofisPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better?

  2. As we know the number must not be divisible by any number > n / 2, we can immediately cut the total iterations half by dividing only up to n / 2. Could we still do better?

题意:查询比n以内的素数的个数。

超时思路:一个一个判断是否为素数。

class Solution {public:int countPrimes(int n) {switch (n){case 0:return 0;case 1:return 1;case 2:return 2;default:break;}int count = 2;for (int i = 3; i <= n; i+=2){if (isPrime(i))count++;}return count;}bool isPrime(int n){for (int i = 2; i*i < n; i++){if (n % i == 0)return false;}return true;}};

AC思路:素数筛法,埃拉托斯特尼筛选法,把质数的倍数全给标记掉,返回质数个数。

class Solution {public:int countPrimes(int n) {bool* isprime = new bool[n];for (int i = 2; i < n; i++)isprime[i] = true;int count = 0;for (int i = 2; i < n; i++){if (isprime[i]){count++;for (int j = i; j < n; j += i){isprime[j] = false;}}}return count;}};






0 0
原创粉丝点击