Leetcode——204. Count Primes

AI权益加码!Claude Code、Cursor等20+工具免费用! 购周边限时加赠Coding Plan Lite,畅享主流AI工具!学习进阶更高效! 阅读详情

题目

Description:

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

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 of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better?

Show More Hint

解答

寻找小于一个数的所有质数(素数:prime)

Two methods.

  1. traverse the number from 2 to n, judge whether the number is prime or not.
    1. How we know whether the number is a prime?
    2. if the number is divisible by one of the number from 2 to n/2(sqrt(n)), it is not prime, if not, it is prime.
    3. The complexity is O(N^2) or O(N^1.5)
  2. The second amazing method is Sieve of Eratosthenes!!!
    1. Create a list of consecutive integers from 2 through n:(2,3,4,…,n)
    2. Initially, let p equal 2,the smallest prime number.
    3. Enumerate the multiples of p by counting to n from 2p in increments of p, and mark them in the list(these will be 2p,3p,4p,…; the p iteself should not be marked).
    4. Find the first number that is greater than p in the list that is not marked, stop. Otherwise, let p now equal this new number (which is the next prime), and repeat from step 3.

Code:

class Solution1 {//O(N^2)
public:
    int countPrimes(int n) {
        int count=0;
        if(n==1) return 0;
        for(int i=2;i<n;i++)
            if(isPrime(i))
                count++;
        return count;
    }
private:
    bool isPrime(int n)//judge whether n is a prime number or not
    {
        for(int i=2;i<=n/2;i++)
        {
            if(n%i==0) return false;
        }
        return true;
    }
};
class Solution2 {//O(N^1.5),也是超时
public:
    int countPrimes(int n) {
        int count=0;
        if(n==1) return 0;
        for(int i=2;i<n;i++)
            if(isPrime(i))
                count++;
        return count;
    }
private:
    bool isPrime(int n)//judge whether n is a prime number or not
    {
        for(int i=2;i<=sqrt(n);i++)
        {
            if(n%i==0) return false;
        }
        return true;
    }
};
class Solution3 {// Sieve of Eratosthenes. https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
public:
    int countPrimes(int n) {
        if(n<2) return 0;
        int count=0;
        bool isPrime[n]={0};//0 represents the number is prime
        for(int p=2;p<n;p++)
        {
            if(!isPrime[p])
            {
                count++;
                for(int j=p*2;j<n;j+=p)
                {
                    isPrime[j]=true;
                }
            }
        }
        return count;
    }

};
class Solution {// Sieve of Eratosthenes. https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
public:
    int countPrimes(int n) {
        if(n<=2) return 0;
        int count=0;
        bool isPrime[n]={0};//0 represents the number is prime
        for(int p=2;p<n;p++)
        {
            if(!isPrime[p])
            {
                count++;
                if(p>sqrt(n)) continue;
                for(int j=p*p;j<n;j+=p)
                {
                    isPrime[j]=true;
                }
            }
        }
        return count;
    }

};
LeetCode 204. Count Primes 及判断一个数是否是质数的方法 LeetCode 204. Count Primes 题意:给出一个非负整数n,求小于n的质数的个数。 阅读详情

相关推荐

leetcode 204: Count Primes

Description: Count the number of prime numbers less than a non-negative number, n [思路] 素数不能被比它小的整数整除, 建一个boolean 数组, 从2开始, 把其倍数小于N的都删掉. 注意 inner loop从i开始, 比i小的会在以前就被check过. [CODE] pu

西施豆腐渣 1万+

Leetcode题解 204. Count Primes

Description:Count the number of prime numbers less than a non-negative number, n.厄拉多塞筛法public class Solution { public int countPrimes(int n) { int[] res=new int[n]; int count=0;

Xd_Yu的专栏 468

LeetCode204:Count Primes

Description:Count the number of prime numbers less than a non-negative number, n.计算小于n的非负整数中素数的个数。 素数又称质数,是指只能被1和它自身相除的自然数。需要注意的是1既不是素数也不是合数。2是最小的素数。使用判断一个数是否是素数的函数,那么这个函数需要进行一轮循环,在给定的小于n中又要进行一轮循环。所以时

816

leetcode204. Count Primes

Description:Count the number of prime numbers less than a non-negative number, n. java public class Solution { public int countPrimes(int n) { boolean[] a= new boolean[n]; for (in

大锅八十小锅四十 406

LEETCODE204-Count Primes

Description: Count the number of prime numbers less than a non-negative number, n. 思路: The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n. 

aliceyangxi1987的博客 582

LeetCode - 204. Count Primes

题目 LeetCode - 204. Count Primes 题目链接 https://leetcode.com/problems/count-primes/ 参考博客 https://www.cnblogs.com/grandyang/p/4462810.html 解题思路 自行设计的算法时间复杂度是n∗n\sqrt{n} * nn​∗n,但是运行超时,参考博客的算法复杂度分析知时间复杂度相同...

virgilshi的博客 214

[LeetCode]204. Count Primes

[LeetCode]204. Count Primes题目描述思路类似动态规划,每次计算当前素数时,将不可能是素数的结果标记,之后遍历碰到这些结果直接跳过代码#include <iostream> #include <vector>using namespace std;class Solution { public: int countPrimes(int n) { if

Lcharon的博客 361

[leetcode] 204. Count Primes

Description 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. 分析 题目的意思是:给你一个...

Learning from the mistakes 209

Leetcode 204.Count Primes

Leetcode 204. Count Primes Count the number of prime numbers less than a non-negative number, n. 知识:任意一个合数都可以进行质因数分解,即任意一个合数都是一个小于自己的素数的倍数。 一、试除法 进行打表,一个数n如果是比它小的任意一个素数的倍数,则它是合数。 复杂度O(...

yangchz的博客 393

LeetCode204 Count Primes 详解!

关于求n以内的素数有很多种方法,如果要列出素数来的话我们尝试着把根号n以内的数除一遍就可以了,但是对于筛选法比如我们去掉2的倍数,3的倍数…等等也是极为巧妙的。LeetCode204这道题目所要的是不大于n的素数个数,这里看完讨论区的大神代码——我们计算个数的时候使用筛选法并且可以不用遍历整个数组,使我受益匪浅,但是美中不足的是所给代码并没有注释,刚开始看的时候也是极其懵逼,后面耐心的理解并添加...

ni_new_sm_new的博客 274

leetcode刷题记录-204. Count Primes

leetcode刷题记录-204. Count Primes

zhaizhan501的博客 216

面试题素数问题 && Leetcode 204. Count Primes

找到一篇简单粗暴的介绍面试质素算法的文章。 然后就涉及到如何按位保存。 在C++里,要按照bit来存储可以使用容器bitset。但是需要预先指定长度,例如bitset bar。 要动态分配长度,可以使用vector,它会优化,长度可能为1bit。但是实际操作中发现不好用,不能与bool类型的值判等,也不能赋值(可能是我没搞懂,但在微软对该类的介绍页面也没看到相关用法,只有用cout输

GTMer的专栏 257

Leetcode204-Count Primes

这个题相当于求小于n的所有质数,曾在编程之美中看到过一个求一组质数的算法,叫厄拉多塞筛法,时间复杂度仅有O(nloglogn),这是一个相当好的算法(如果从1到n-1分别判断质数,时间复杂度为O(n*sqrt(n)))。 厄拉多塞筛法的步骤:建立从2到n的集合G={2, 3, 4, ..., n},每次从集合中取出最小的数A,这个数就是质数;然后将数A * times从集合中删除,其中1<=times<=n/A。得到一个新的集合G',重复上述步骤直到集合为空,就取出了所有质数。

coderhuhy的专栏 912

LeetCode 204: Count Primes

LeetCode 204: Count Primes 题目描述 给定一个非负整数,计算小于该整数的所有素数(最小的素数为2)。 解题思路 该题的解法有一个特定的名字:埃拉托斯特尼筛法,下面简单说一下,具体可以参阅网上的资料。 判断一个数x是否是合数,只要依次除以2至sqrt(x)间的素数,判断是否整除即可。 埃拉托斯特尼筛法基于以下原理,给定一个素数n>1,kn是一个合数(k&g...

HakunaMatata的博客 163

Leetcode204. Count Primes

题目地址: https://leetcode.com/problems/count-primes/ 给定nnn非负,问小于nnn的素数个数。 法1:埃拉托斯特尼筛法(Sieve of Eratosthenes)。开一个长度为nnn的boolean数组记录每个数是否是素数。首先全填充为true,将000和111置为false。接着开始找第一个是true的数,是222,接着把222的比自己大的倍数全标记为false;接着再向后找是true的数,然后重复上面的操作。这样小于nnn的所有非素数就全被标记为false

数学、算法爱好者的博客 257

Leetcode_204_Count Primes

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/46366207 Description: Count the number of prime numbers less than a non-negative number, n. 思路: (1)题意为给定整数n,求解n以内的整数中有多少个素数(质数)。 (2)该题涉及到数学相关的知识。首先,看下素数的定义:质数(prime

皮斯特劳沃 1345

LeetCode 204:Count Primes

Description: Count the number of prime numbers less than a non-negative number, n 分析: 题目要求计算小于N的所有素数的个数。所有主程序很简单:判断是否是素数字,如是,count++ (暂且忽略prim_vec, 后面判断素数时会用到): int countPrimes(int n) {

哈哈的个人专栏 4170

LeetCode 204 Count Primes

题目描述Description:Count the number of prime numbers less than a non-negative number, n.Credits: Special thanks to @mithmatt for adding this problem and creating all test cases.分析这道题,直接看hint即可!Hint: Let’

Yano_nankai的博客 587

LeetCode204——Count Primes

Description: Count the number of prime numbers less than a non-negative number, n. Credits: Special thanks to @mithmatt for adding this problem and creating all test cases. 实现: int countPrim

代码菌的blog 1634
上一篇: Leetcode——242. Valid Anagram
下一篇: Leetcode——202. Happy Number
路漫远吾求索
博客等级 码龄14年 434粉丝 162原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值