【LeetCode】 204. Count Primes 解题报告(Python & C++)
作者: 负雪明烛
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++)的更多相关文章
- [LeetCode] 204. Count Primes 解题思路
Count the number of prime numbers less than a non-negative number, n. 问题:找出所有小于 n 的素数. 题目很简洁,但是算法实现的 ...
- [leetcode] 204. Count Primes 统计小于非负整数n的素数的个数
题目大意 https://leetcode.com/problems/count-primes/description/ 204. Count Primes Count the number of p ...
- [LeetCode] 204. Count Primes 质数的个数
Count the number of prime numbers less than a non-negative number, n. Example: Input: 10 Output: 4 E ...
- [LeetCode] 204. Count Primes 计数质数
Description: Count the number of prime numbers less than a non-negative number, n click to show more ...
- Java [Leetcode 204]Count Primes
题目描述: Description: Count the number of prime numbers less than a non-negative number, n. 解题思路: Let's ...
- Java for LeetCode 204 Count Primes
Description: Count the number of prime numbers less than a non-negative number, n. 解题思路: 空间换时间,开一个空间 ...
- LeetCode 204. Count Primes (质数的个数)
Description: Count the number of prime numbers less than a non-negative number, n. 题目标签:Hash Table 题 ...
- LeetCode 204 Count Primes
Problem: Count the number of prime numbers less than a non-negative number, n. Summary: 判断小于某非负数n的质数 ...
- (easy)LeetCode 204.Count Primes
Description: Count the number of prime numbers less than a non-negative number, n. Credits:Special t ...
随机推荐
- MySQL_集群
管理节点:192.168.31.66 sql节点1+data1节点:192.168.31.42 sql节点2+data2节点:192.168.31.128 llll
- Excel-vlookup(查找值,区域范围,列序号,0)如何固定住列序列号,这样即使区域范围变动也不受影响
突然,发现VLOOKUP的列序列号并不会随着区域范围的改变而自动调节改变,只是傻瓜的一个数,导致V错值.所有,就想实现随表格自动变化的列序号. 方法一:在列序号那里,用函数得出永远想要的那个列在区域范 ...
- mysql数据定义语言DDL
库的管理 创建 create 语法:create database 库名 [character set 字符集] # 案例:创建库 create database if not exists book ...
- pow()是如何实现的?
如1.5 ** 2.5,如何计算?似乎是这样的: 1. cmath calculates pow(a,b) by performing exp(b * log(a)). stackoverflow 2 ...
- c++ cmake及包管理工具conan简单入门
cmake是一个跨平台的c/c++工程管理工具,可以通过cmake轻松管理我们的项目 conan是一个包管理工具,能够自动帮助我们下载及管理依赖,可以配合cmake使用 这是一个入门教程,想深入了解的 ...
- Kafka入门教程(一)
转自:https://blog.csdn.net/yuan_xw/article/details/51210954 1 Kafka入门教程 1.1 消息队列(Message Queue) Messag ...
- 大数据学习day25------spark08-----1. 读取数据库的形式创建DataFrame 2. Parquet格式的数据源 3. Orc格式的数据源 4.spark_sql整合hive 5.在IDEA中编写spark程序(用来操作hive) 6. SQL风格和DSL风格以及RDD的形式计算连续登陆三天的用户
1. 读取数据库的形式创建DataFrame DataFrameFromJDBC object DataFrameFromJDBC { def main(args: Array[String]): U ...
- 什么是 IP 地址 – 定义和解释
IP 地址定义 IP 地址是一个唯一地址,用于标识互联网或本地网络上的设备.IP 代表"互联网协议",它是控制通过互联网或本地网络发送的数据格式的一组规则. 本质上,IP 地址是允 ...
- 容器之分类与各种测试(四)——unordered-multimap
unordered-multiset与unordered-multimap的区别和multiset与multimap的区别基本相同,所以在定义和插入时需要注意 key-value 的类型. 例程 #i ...
- Linux FTP的主动模式与被动模式
Linux FTP的主动模式与被动模式 一.FTP主被动模式 FTP是文件传输协议的简称,ftp传输协议有着众多的优点所以传输文件时使用ftp协议的软件很多,ftp协议使用的端口是21( ...