【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 = 12
As 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;
- }
- 2 × 6 = 12
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. ...
随机推荐
- Seajs demo
index.html <!doctype html> <html lang="en"> <head> <meta charset=&quo ...
- ACM数据结构相关资料整理【未完成,待补充】
在网上总是查不到很系统的练ACM需要学习的数据结构资料,于是参考看过的东西,自己整理了一份. 能力有限,欢迎大家指正补充. 分类主要参考<算法竞赛入门经典训练指南>(刘汝佳),山东大学数据 ...
- poj 1325 Machine Schedule 二分匹配,可以用最大流来做
题目大意:机器调度问题,同一个任务可以在A,B两台不同的机器上以不同的模式完成.机器的初始模式是mode_0,但从任何模式改变成另一个模式需要重启机器.求完成所有工作所需最少重启次数. ======= ...
- JS身份证真实性校验(二)
var Wi = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1 ]; // 加权因子 var ValideCode = [ 1, 0 ...
- SPOJ 422 Transposing is Even More Fun(polay计数)
题目链接:http://www.spoj.com/problems/TRANSP2/ 题意: 思路:不妨设a=1,b=2, 我们发现(001,010,100)组成一个置换,(011,110,101)组 ...
- emplace_back减少内存拷贝和移动
--------<深入应用C++11:代码优化与工程级应用>第2章使用C++11改进程序性能,本章将分别介绍右值引用相关的新特性.本节为大家介绍emplace_back减少内存拷贝和移动. ...
- .NET 实现异步处理的集中方式
对于异步,相信大家都不十分陌生.准确点来说就是方法执行后立即返回,待到执行完毕会进行通知.就是当一个任务在执行的时候,尤其是需要耗费很长的时间进行处理的任务,如果利用单线程进行操作的话,势必造成界面的 ...
- design pattern及其使用
什么是设计模式? design pattern是一个通用的,可以被重用的关于一个常见的问题的解决方案. 为什么要用设计模式? 引入设计模式的理论基础非常简单.我们每天都会碰到问题.我们可能碰到决定使用 ...
- HDU 1240 (简单三维广搜) Asteroids!
给出一个三维的迷宫以及起点和终点,求能否到大终点,若果能输出最短步数 三维的问题无非就是变成了6个搜索方向 最后强调一下xyz的顺序,从输入数据来看,读入的顺序是map[z][x][y] 总之,这是很 ...
- [转] POJ数学问题
转自:http://blog.sina.com.cn/s/blog_6635898a0100magq.html 1.burnside定理,polya计数法 这个大家可以看brudildi的<组合 ...