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

Hint:

    1. 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?

    2. 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?

    3. 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;
      }
    4. 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?

    5. 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?

    6. 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 pp2 + pp2 + 2p, ... Now what should be the terminating loop condition?

    7. 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?

    8. 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的更多相关文章

  1. 【LeetCode】 204. Count Primes 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 素数筛法 参考资料 日期 [LeetCode] 题目 ...

  2. 【刷题-LeetCode】204. Count Primes

    Count Primes Count the number of prime numbers less than a non-negative number, *n*. Example: Input: ...

  3. 【LeetCode】222. Count Complete Tree Nodes 解题报告(Python)

    [LeetCode]222. Count Complete Tree Nodes 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个 ...

  4. 【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 ...

  5. 【LeetCode】730. Count Different Palindromic Subsequences 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 记忆化搜索 动态规划 日期 题目地址:https:/ ...

  6. 【LeetCode】696. Count Binary Substrings 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:暴力解法(TLE) 方法二:连续子串计算 日 ...

  7. 【LeetCode】357. Count Numbers with Unique Digits 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  8. 【LeetCode】38 - Count and Say

    The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 111221, ...

  9. 【Leetcode】357. Count Numbers with Unique Digits

    题目描述: Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n. ...

随机推荐

  1. Linux系统文件的隐藏属性

    linux系统的文件除了有普通rwx权限外还有一种隐藏权限,例如明明有权限删除某个文件却报错了. 或者仅能为某个文件追加内容而不能减少内容,遇到这种很‘奇怪’的文件,就要怀疑是文件被设置隐藏权限了. ...

  2. CactiEZ命令行添加主机监控参考

    1.添加主机 php -q add_device.php --description= --community="public" 查询主机模板: php -q add_device ...

  3. [置顶] ArcGIS10.1完美破解步骤详细图文教程

    ArcGIS软件安装其实都比较简单的,只要大家清楚每个步骤,顺序安装即可.但是安装过程要注意一些问题,license先安装,安装完成先停止服务,然后再安装desktop.完成后就是破解步骤了,很多同学 ...

  4. SPA与DPA 攻击【转】

    转自:http://blog.sina.com.cn/s/blog_6cb58dbf0102v7ym.html SPA SPA是一种直接解释能量消耗测定值的技术.系统消耗能量的大小随微处理器执行的指令 ...

  5. 《Linux/Unix系统编程手册》读书笔记9(文件属性)

    <Linux/Unix系统编程手册>读书笔记 目录 在Linux里,万物皆文件.所以文件系统在Linux系统占有重要的地位.本文主要介绍的是文件的属性,只是稍微提及一下文件系统,日后如果有 ...

  6. 《大道至简-Team》

    已经学习了<大道至简>两章,我们了解了编程的本质和“懒人”造就了方法.书中没有提供给我们编程的技巧,捷径,而是从别的方面为我们讲解了编程的精义.第三章就为我们引入了“团队”这个概念. 我们 ...

  7. How to install cacti With Nginx

    转载于:https://github.com/blackyboy/Ubuntu-Linux-Stuffs/blob/master/How-to-install-Cacti-Monitoring-Ser ...

  8. 【HDOJ】5446 Unknown Treasure

    1. 题目描述题目很简单,就是求$C(n,m) % M$. 2. 基本思路这是一道应用了众多初等数论定理的题目,因为数据范围较大因此使用Lucas求$C(n,m) % P$.而M较大,因此通过$a[i ...

  9. hibernate学习笔记4---HQL、通用方法的抽取实现

    一.通用方法的抽取实现 由于hibernate中对增删改查的一切操作都是面向对象的,所以将增删改查抽取成通用方法,以满足不同的表的增删改查操作,简化jdbc代码. 具体例子如下: package cn ...

  10. java生成带html样式的word文件

    参考:http://blog.csdn.net/xiexl/article/details/6652230 最近在项目中需要将通过富文本编辑器处理过的文字转换为Word,查了很久,大家通常的解决办法是 ...