作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


[LeetCode]

题目地址:https://leetcode.com/problems/count-primes/

Total Accepted: 36655 Total Submissions: 172606 Difficulty: Easy

题目描述

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的素数有多少个。

解题方法

素数筛法

http://blog.csdn.net/blitzskies/article/details/45442923 提示用Sieve of Eratosthenes的方法。

素数筛法就是把这个数的所有倍数都删除掉,因为这些数一定不是素数。最后统计一下数字剩余的没有被删除的个数就好。

也是学习了。

Java解法。

重点是优化效率,每一步的效率都要优化。

用List都会效率低,最后用数组好了。

/**
* 统计质数的数目。使用数组,用列表效率低。
*
* @param n
* @return
*/
public static int countPrimes3(int n) { //n个元素的数组,其实只用到了n-2个。多见了2个防止输入0的时候崩溃。
int[] nums = new int[n];
//把所有的小于n的大于2的数字加入数组里
for (int i = 2; i < n; i++) {
//注意计算质数从2开始的,而数组从0开始
nums[i - 2] = i;
}
//统一的长度,优化计算
int size = nums.length;
//各种优化效率,只计算到sqrt(n)
for (int i = 0; i * i < size; i++) {
//获取数组中的数字
int temp = nums[i];
//如果不是0,则进行计算,否则直接跳过,因为这个数已经是之前的某数字的倍数
if (temp != 0) {
//把该数字的倍数都删去,因为他们都不是质数
//int i1 = temp - 1 优化效率,是因为比如用5来删除数字的时候15=3*5已经被删除过了,所以从20=5*4开始删除
for (int i1 = temp - 1; i + temp * i1 < size; i1++) {
//如果这个数不是素数则被置0,置成其他的负数也一样,只是为了区分和统计
//i + temp * i1,i是因为从当前数字开始,比如10是从5的位置开始计算位置
nums[i + temp * i1] = 0;
}
}
}
return countNums(nums);
} /**
* 计算数组中的0出现了多少次
*
* @param nums
* @return
*/
public static int countNums(int[] nums) {
int size = nums.length;
int zeros = 0;
for (int num : nums) {
if (num == 0) {
zeros++;
}
} return size - zeros;
}

没必要把所有的数字都保存到一个数组里面,可以直接记录和数字对应的位置的数字是不是质数。如果不是质数,则在对应位置保存true.最后统计不是true的,即质数的个数即可。

这个方法可以通用下去。类似的统计的题目只记录对应的位置是否满足条件,最后统计符合条件的个数。

/**
* 统计质数的数目。使用数组,用列表效率低。
*
* @param n
* @return
*/
public static int countPrimes4(int n) { //n个元素的数组,其实只用到了n-2个。多见了2个防止输入0的时候崩溃。
boolean[] nums = new boolean[n];
//各种优化效率,只计算到sqrt(n)
for (int i = 2; i * i < n; i++) {
//获取数组中的数字是不是为0
//不是质数则为true
boolean temp = nums[i];
//如果不是true,说明不是质数,则进行计算,否则直接跳过,因为这个数已经是之前的某数字的倍数
if (!temp) {
//把该数字的倍数都删去,因为他们都不是质数
//int i1 = temp - 1 优化效率,是因为比如用5来删除数字的时候15=3*5已经被删除过了,所以从20=5*4开始删除
for (int j = i; i * j < n; j++) {
//如果这个数不是素数则被置true
//i + temp * i1,i是因为从当前数字开始,比如10是从5的位置开始计算位置
nums[i * j] = true;
}
}
}
return countNums2(nums);
} /**
* 计算数组中的不是素数的false出现了出现了多少次
*
* @param nums
* @return
*/
public static int countNums2(boolean[] nums) {
int notZeros = 0;
for (int i = 2; i < nums.length; i++) {
if (!nums[i]) {
notZeros++;
}
} return notZeros;
}

二刷,使用Python解法,速度很慢,勉强通过了。

class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
nums = [True] * n
for i in xrange(2, n):
j = 2
while i * j < n:
nums[i * j] = False
j += 1
res = 0
for i in xrange(2, n):
if nums[i]:
res += 1
return res

C++版本如下:

class Solution {
public:
int countPrimes(int n) {
vector<bool> nums(n, true);
for (int i = 2; i < n; i++) {
int j = 2;
while (i * j < n) {
nums[i * j] = false;
j ++;
}
}
int res = 0;
for (int i = 2; i < n; i++) {
if (nums[i]){
res ++;
}
}
return res;
}
};

C++数组初始化需要使用memset,而且数组的大小n不能是0,数组解法如下。

class Solution {
public:
int countPrimes(int n) {
if (n <= 0) return false;
bool nums[n];
memset(nums, true, sizeof(nums));
for (int i = 2; i < n; i++) {
int j = 2;
while (i * j < n) {
nums[i * j] = false;
j ++;
}
}
int res = 0;
for (int i = 2; i < n; i++) {
if (nums[i]){
res ++;
}
}
return res;
}
};

参考资料

http://blog.csdn.net/blitzskies/article/details/45442923

https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#cite_note-horsley-1

http://blog.csdn.net/xudli/article/details/45361471

日期

2015/10/19 23:38:24
2018 年 11 月 29 日 —— 时不我待

【LeetCode】 204. Count Primes 解题报告(Python & C++)的更多相关文章

  1. [LeetCode] 204. Count Primes 解题思路

    Count the number of prime numbers less than a non-negative number, n. 问题:找出所有小于 n 的素数. 题目很简洁,但是算法实现的 ...

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

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

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

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

  4. [LeetCode] 204. Count Primes 计数质数

    Description: Count the number of prime numbers less than a non-negative number, n click to show more ...

  5. Java [Leetcode 204]Count Primes

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

  6. Java for LeetCode 204 Count Primes

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

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

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

  8. LeetCode 204 Count Primes

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

  9. (easy)LeetCode 204.Count Primes

    Description: Count the number of prime numbers less than a non-negative number, n. Credits:Special t ...

随机推荐

  1. shell 的 功能语句--1

    [1]说明性语句 (1)shell 程序和语句 shell 程序由零或多条shell语句构成. shell语句包括三类:说明性语句.功能性语句和结构性语句. 说明性语句: 以#号开始到该行结束,不被解 ...

  2. .NET SAAS 架构与设计 -SqlSugar ORM

    1.数据库设计 常用的Saas分库分为2种类型的库 1.1 基础信息库 主要存组织架构 .权限.字典.用户等 公共信息 性能优化:因为基础信息库是共享的,所以我们可以使用 读写分离,或者二级缓存来进行 ...

  3. C# CheckBoxList-DropDownList回显、筛选回显

    <asp:CheckBoxList ID="ddlType" runat="server" RepeatColumns="10" Re ...

  4. 基于 Golang 构建高可扩展的云原生 PaaS(附 PPT 下载)

    作者|刘浩杨 来源|尔达 Erda 公众号 ​ 本文整理自刘浩杨在 GopherChina 2021 北京站主会场的演讲,微信添加:Erda202106,联系小助手即可获取讲师 PPT. 前言 当今时 ...

  5. 在idea的java开发中字符串length()方法获取长度与赋值不符的问题

    最近在开发中用到length()方法获取中文字符串的长度,发现获得的长度与实际不符.比如个String类型赋值为"中",但获取长度却是2. 这让我百思不得其解,后来突然想起来我在研 ...

  6. day07 Nginx入门

    day07 Nginx入门 Nginx简介 Nginx是一个开源且高性能.可靠的http web服务.代理服务 开源:直接获取源代码 高性能:支持海量开发 可靠:服务稳定 特点: 1.高性能.高并发: ...

  7. 【DFS与BFS】洛谷 P1135 奇怪的电梯

    题目:奇怪的电梯 - 洛谷 (luogu.com.cn) 因为此题数据范围较小,有dfs及bfs等多种做法. DFS 比较正常的dfs,注意vis数组一定要回溯,不然会漏情况 例如这个数据 11 1 ...

  8. android studio 报 Error:(79) Error parsing XML: not well-formed (invalid token)

    android studio 报 Error:(79) Error parsing XML: not well-formed (invalid token) 我的原因是因为string 里面有< ...

  9. mybatis-plus解析

    mybatis-plus当用lambda时bean属性不要以is/get/set开头,解析根据字段而不是get/set方法映射

  10. Java实现单链表的增删查改及逆置打印

    //所提供的接口 LinkList.java package Struct; public interface LinkList {//判断链表为空public boolean linkListIsE ...