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. MS WORD 表格自动调整列宽,自动变漂亮,根据内容自动调整 .

    在MS WORD中,当有大量的表格出现时,调整每个表格的的高和宽和大小将是一件非常累的事情,拖来拖去,非常耗时间,而且当WORD文档达到300页以上时,调整反应非常的慢,每次拖拉线后,需要等待一段时间 ...

  2. 【资料分享】 OpenCV精华收藏

    OpenCV精华收藏 SkySeraph Dec.29th 2010  HQU Email:zgzhaobo@gmail.com    QQ:452728574 Latest Modified Dat ...

  3. Write operations are not allowed in read-only mode

    使用Spring提供的Open Session In View而引起Write operations are not allowed in read-only mode (FlushMode.NEVE ...

  4. 《c程序设计语言》读书笔记--子函数原型和声明的形参

    #include <stdio.h> #define Num 20 int power(int base,int n) { int p = 1; int i; for(i = 0;i &l ...

  5. 域用户直接登陆(C#,MVC)

    域用户直接登陆MVC网页,未做测试,待测试后进行细化和补充 1. 服务器与客户端必须在同一个域名下. 2. WEB.CONFIG文件中的身份验证方式,使用Windows身份验证: 3. IIS的网站属 ...

  6. 如何实现wpf的多国语言

    http://www.cnblogs.com/horan/archive/2012/04/20/wpf-multilanguage.html 4.0版本的locbaml http://michaels ...

  7. [转载]流式大数据处理的三种框架:Storm,Spark和Samza

    许多分布式计算系统都可以实时或接近实时地处理大数据流.本文将对三种Apache框架分别进行简单介绍,然后尝试快速.高度概述其异同. Apache Storm 在Storm中,先要设计一个用于实时计算的 ...

  8. 30个实用的Linux find命令

    除了在一个目录结构下查找文件这种基本的操作,你还可以用find命令实现一些实用的操作,使你的命令行之旅更加简易.本文将介绍15种无论是于新手还是老鸟都非常有用的Linux find命令 . 首先,在你 ...

  9. Jqgrid入门-Jqgrid分组的实现(八)

    上一章主要说明了如果实现Jqgrid列数据拖动,这一章主要讨论在Jqgrid中如何实现分组功能.         类似于Sql语句的Group By,Jqgrid提供了属性实现数据分组,这样表现数据会 ...

  10. [swustoj 243] 又是一年CET46

    又是一年CET46(0243) 问题描述 CET46 成绩出来啦,一群学生在谈论他们的成绩.A说他的成绩比B高,B说他的成绩比C低,D说他的成绩和E一样…… 他们当中可能有人在说谎.你的任务就是判断是 ...