【LeetCode】204 - Count Primes
Description:Count the number of prime numbers less than a non-negative number, n.
Hint:
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?
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?
Let's write down all of 12's factors:
2 × 6 = 12
3 × 4 = 12
4 × 3 = 12
6 × 2 = 12As you can see, calculations of 4 × 3 and 6 × 2 are not necessary. Therefore, we only need to consider factors up to √n because, if n is divisible by some number p, then n = p × q and since p ≤ q, we could derive that p ≤ √n.
Our total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach?
public int countPrimes(int n) {
int count = 0;
for (int i = 1; i < n; i++) {
if (isPrime(i)) count++;
}
return count;
} private boolean isPrime(int num) {
if (num <= 1) return false;
// Loop's ending condition is i * i <= num instead of i <= sqrt(num)
// to avoid repeatedly calling an expensive function sqrt().
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
}The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n. But don't let that name scare you, I promise that the concept is surprisingly simple.
Sieve of Eratosthenes: algorithm steps for primes below 121. "Sieve of Eratosthenes Animation" by SKopp is licensed under CC BY 2.0.We start off with a table of n numbers. Let's look at the first number, 2. We know all multiples of 2 must not be primes, so we mark them off as non-primes. Then we look at the next number, 3. Similarly, all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ... must not be primes, so we mark them off as well. Now we look at the next number, 4, which was already marked off. What does this tell you? Should you mark off all multiples of 4 as well?
4 is not a prime because it is divisible by 2, which means all multiples of 4 must also be divisible by 2 and were already marked off. So we can skip 4 immediately and go to the next number, 5. Now, all multiples of 5 such as 5 × 2 = 10, 5 × 3 = 15, 5 × 4 = 20, 5 × 5 = 25, ... can be marked off. There is a slight optimization here, we do not need to start from 5 × 2 = 10. Where should we start marking off?
In fact, we can mark off multiples of 5 starting at 5 × 5 = 25, because 5 × 2 = 10 was already marked off by multiple of 2, similarly 5 × 3 = 15 was already marked off by multiple of 3. Therefore, if the current number is p, we can always mark off multiples of p starting at p2, then in increments of p: p2 + p, p2 + 2p, ... Now what should be the terminating loop condition?
It is easy to say that the terminating loop condition is p < n, which is certainly correct but not efficient. Do you still remember Hint #3?
Yes, the terminating loop condition can be p < √n, as all non-primes ≥ √n must have already been marked off. When the loop terminates, all the numbers in the table that are non-marked are prime.
class Solution {
public: int countPrimes(int n) {
if(n<=)return ;
int count=;
vector<bool> isPrime(n,true); for(int i=;i<n;i++){
if(isPrime[i]){
count++;
for(long long j=(long long)i*i;j<n;j+=i) //两个longlong必不可少,否则会运行时错误,当i很大时,i*i超出int范围
isPrime[(int)j]=false;
}
}
return count;
} };
【LeetCode】204 - Count Primes的更多相关文章
- 【LeetCode】 204. Count Primes 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 素数筛法 参考资料 日期 [LeetCode] 题目 ...
- 【刷题-LeetCode】204. Count Primes
Count Primes Count the number of prime numbers less than a non-negative number, *n*. Example: Input: ...
- 【LeetCode】222. Count Complete Tree Nodes 解题报告(Python)
[LeetCode]222. Count Complete Tree Nodes 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个 ...
- 【leetcode❤python】 204. Count Primes
#-*- coding: UTF-8 -*- #Hint1:#数字i,i的倍数一定不是质数,因此去掉i的倍数,例如5,5*1,5*2,5*3,5*4,5*5都不是质数,应该去掉#5*1,5*2,5*3 ...
- 【LeetCode】730. Count Different Palindromic Subsequences 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 记忆化搜索 动态规划 日期 题目地址:https:/ ...
- 【LeetCode】696. Count Binary Substrings 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:暴力解法(TLE) 方法二:连续子串计算 日 ...
- 【LeetCode】357. Count Numbers with Unique Digits 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...
- 【LeetCode】38 - Count and Say
The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 111221, ...
- 【Leetcode】357. Count Numbers with Unique Digits
题目描述: Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n. ...
随机推荐
- chrome开发配置(二)获取源代码
1.下载源代码,这里使用最简单的下载,chrome打包好的共享在百度云盘,点击下载 2.建议下载7z压缩工具解压压缩包,大概1个多小时. 3.至于以后怎么更新到最新版不能,等编译生成成功了,我们再具体 ...
- CNN卷积神经网络在自然语言处理的应用
摘要:CNN作为当今绝大多数计算机视觉系统的核心技术,在图像分类领域做出了巨大贡献.本文从计算机视觉的用例开始,介绍CNN及其在自然语言处理中的优势和发挥的作用. 当我们听到卷积神经网络(Convol ...
- SQL server performance - tempdb
When tempdb is used? User objects: User-defined tables and indexes System tables and indexes Global ...
- Docker+K8S实践
一.运维角度: (一)镜像: 1. 避免依赖过深.不要在基础镜像上加太多产生其他的镜像,我觉得这块最多是三四层. 一层是base景像再往上是工具.中间件这样的,再往上一层就是你自己的程序,再多就比较乱 ...
- IRQ和FIQ中断的区别【转】
转自:http://blog.csdn.net/michaelcao1980/article/details/19542039 FIQ和IRQ是两种不同类型的中断,ARM为了支持这两种不同的中断,提供 ...
- dojo 三 类和继承 dojo/_base/declare
这里要讲有关类的定义.继承和实现.官方教程:http://dojotoolkit.org/documentation/tutorials/1.7/declare/类的声明是通过declare 这个方法 ...
- 在windows系统上安装VMware Workstation虚拟机,然后在虚拟机VMware Workstation上安装linux系统,在linux系统安装xshell的服务端,在windows系统上安装xshell。用windows系统上的xshell连接到linux
第一步:安装xshell: 去百度 xshell ,然后安装一下就可以了.就是普通的软件安装,在这里不做过多的接收. 第二步:安装虚拟机VMware Workstation 百度安装,不做过介绍 ...
- SPOJ 1487 Query on a tree III(划分树)
题目链接:http://www.spoj.com/problems/PT07J/ 题意:给出一个有根树,1为根节点,每个节点有权值.若干询问,询问以u为根的子树中权值第K小的节点编号. 思路:DFS一 ...
- UVa 11468 (AC自动机 概率DP) Substring
将K个模板串构成一个AC自动机,那些能匹配到的单词节点都称之为禁止节点. 然后问题就变成了在Tire树上走L步且不经过禁止节点的概率. 根据全概率公式用记忆化搜索求解. #include <cs ...
- HDU 1513 Palindrome
题目就是给一个字符串问最少插入多少个字符能让原字符串变为回文字符串. 算法: 用原串的长度减去原串与翻转后的串的最大公共字串的长度,就是所求答案. //#define LOCAL #include & ...