Description:

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

click to show more hints.

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

计数出小于非负整数n的质数数量。质数(prime number)又称素数,有无限个。质数定义为在大于1的自然数中,除了1和它本身以外不再有其他因数。

解法:埃拉托斯特尼筛法 Sieve of Eratosthenes

如果一个数是另一个数的倍数,那这个数肯定不是质数。利用这个性质,可以建立一个质数数组,从2开始将素数的倍数都标注为不是质数。第一轮将4、6、8等表为非质数,然后遍历到3,发现3没有被标记为非质数,则将6、9、12等标记为非质数,一直到N为止,再数一遍质数数组中有多少质数。

Java:

public class Solution {
public int countPrimes(int n) {
boolean[] prime = new boolean[n];
Arrays.fill(prime, true);
for(int i = 2; i < n; i++){
if(prime[i]){
// 将i的2倍、3倍、4倍...都标记为非素数
for(int j = i * 2; j < n; j = j + i){
prime[j] = false;
}
}
}
int count = 0;
for(int i = 2; i < n; i++){
if(prime[i]) count++;
}
return count;
}
}

Python:

class Solution:
# @param {integer} n
# @return {integer}
def countPrimes(self, n):
isPrime = [True] * max(n, 2)
isPrime[0], isPrime[1] = False, False
x = 2
while x * x < n:
if isPrime[x]:
p = x * x
while p < n:
isPrime[p] = False
p += x
x += 1
return sum(isPrime)

Python:

class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 2: return 0
vis = [False] * n
for i in range(2, int(n ** 0.5) + 1):
if vis[i]: continue
j = i
while j * i < n:
vis[j * i] = True
j += 1
ans = 0
for i in range(2, n):
if not vis[i]: ans += 1
return ans

C++:

class Solution {
public:
int countPrimes(int n) {
if(!n||n==1) return 0;
vector<bool> isPrime(n,true);
// Loop's ending condition is i * i < n instead of i < sqrt(n)
// to avoid repeatedly calling an expensive function sqrt().
for(int i=2;i*i<n;++i)
{
if(!isPrime[i]) continue;
//填表起点i*i,如3*3,因为3*2已填,步长+i
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;
}
};

  

All LeetCode Questions List 题目汇总

  

[LeetCode] 204. Count Primes 计数质数的更多相关文章

  1. LeetCode 204. Count Primes计数质数 (C++)

    题目: Count the number of prime numbers less than a non-negative number, n. Example: Input: 10 Output: ...

  2. LeetCode 204. Count Primes (质数的个数)

    Description: Count the number of prime numbers less than a non-negative number, n. 题目标签:Hash Table 题 ...

  3. 204 Count Primes 计数质数

    计算所有小于非负整数 n 的质数数量. 详见:https://leetcode.com/problems/count-primes/description/ Java实现: 埃拉托斯特尼筛法:从2开始 ...

  4. [leetcode] 204. Count Primes 统计小于非负整数n的素数的个数

    题目大意 https://leetcode.com/problems/count-primes/description/ 204. Count Primes Count the number of p ...

  5. [LeetCode] 204. Count Primes 质数的个数

    Count the number of prime numbers less than a non-negative number, n. Example: Input: 10 Output: 4 E ...

  6. LeetCode 204 Count Primes

    Problem: Count the number of prime numbers less than a non-negative number, n. Summary: 判断小于某非负数n的质数 ...

  7. Java [Leetcode 204]Count Primes

    题目描述: Description: Count the number of prime numbers less than a non-negative number, n. 解题思路: Let's ...

  8. Java for LeetCode 204 Count Primes

    Description: Count the number of prime numbers less than a non-negative number, n. 解题思路: 空间换时间,开一个空间 ...

  9. Leetcode 204 Count Primes 数论

    题意:统计小于n的质数个数. 作为一个无节操的楼主,表示用了素数筛法,并没有用线性素数筛法. 是的,素数筛法并不是该题最佳的解法,线性素数筛法才是. 至于什么是素数筛法,请百度吧. class Sol ...

随机推荐

  1. Android Binder机制彻底梳理一

    Binder架构图: 先来瞅一下它的整体架构图: 其中粉红部分是上层的Binder,而蓝色的则是下层的Binder,很显然上层的是依赖于下层的. 什么是Binder[有个大概了解]? 这里从几个层面来 ...

  2. axure快速上手

    Axure RP是一个专业的快速原型设计工具.Axure(发音:Ack-sure),代表美国Axure公司:RP则是Rapid Prototyping(快速原型)的缩写.Axure RP是美国Axur ...

  3. pandas 6 时间

    类 备注 创建方法 Timestamp 时刻数据 to_datetime,Timestamp DatetimeIndex Timestamp的索引 to_datetime,date_range,Dat ...

  4. sort()函数中的key

    d = { , , } #for k in d.items(): # print(k) content = list(d.items()) print(content) content.sort(ke ...

  5. java接口的成员变量的修饰符

    前言:c++学的java都忘记了不少 interface(接口)可将其想象为一个"纯"抽象类.它允许创建者规定一个类的基本形式:方法名.自变量列表以及返回类型,但不实现方法主体 接 ...

  6. Codevs 3122 奶牛代理商 VIII(状压DP)

    3122 奶牛代理商 VIII 时间限制: 3 s 空间限制: 256000 KB 题目等级 : 大师 Master 题目描述 Description 小徐是USACO中国区的奶牛代理商,专门出售质优 ...

  7. 洛谷 P1281 书的复制 题解

    P1281 书的复制 题目背景 大多数人的错误原因:尽可能让前面的人少抄写,如果前几个人可以不写则不写,对应的人输出0 0. 不过,已经修改数据,保证每个人都有活可干. 题目描述 现在要把m本有顺序的 ...

  8. 54、Spark Streaming:DStream的transformation操作概览

    一. transformation操作概览 Transformation Meaning map 对传入的每个元素,返回一个新的元素 flatMap 对传入的每个元素,返回一个或多个元素 filter ...

  9. 打造VIM成为IDE - nerdtree

    nerdtree 自动缩进 :set paste :set nopaste set tabstop=4 set softtabstop=4 set shiftwidth=4 set noautoind ...

  10. Postgresql 数据库迁移步骤

    1.操作位置:迁移数据库源(旧数据库主机) 找到PostgreSql 的data目录   关闭数据库进程 打包 tar -zcvf pgdatabak.tar.gz data/ ----------- ...