public class Solution {
public int CountPrimes(int n) {
if (n <= )
{
return ;
} long[] prime = new long[n + ];
bool[] mark = new bool[n + ]; int primeSize = ; for (int i = ; i < n; i++)
{
mark[i] = false;
} for (long i = ; i < n; i++)
{
if (mark[i] == true)
{
continue;
}
prime[primeSize++] = i;
for (long j = i * i; j <= n; j += i)
{
mark[j] = true;
}
} return primeSize;
}
}

https://leetcode.com/problems/count-primes/#/description

这道题目是意思是,计算比n小的非负数中有多少素数。

例如:

n = 7,素数有2,3,5(不包含7)一共3个

n = 8,素数有2,3,5,7一共4个

使用素数筛法可以提高效率。

python的实现如下:

 class Solution:
def countPrimes(self, n: int) -> int:
nfilter = [False] * n
count =
for i in range(,n):
if nfilter[i]:
continue
count +=
k = i + i
while k < n:
nfilter[k] = True
k += i
return count

leetcode204的更多相关文章

  1. LeetCode----204. Count Primes(Java)

    package countPrimes204; /* * Description: * Count the number of prime numbers less than a non-negati ...

  2. LeetCode204:Count Primes

    Description: Count the number of prime numbers less than a non-negative number, n. 比计算少n中素数的个数. 素数又称 ...

  3. [Swift]LeetCode204. 计数质数 | Count Primes

    Count the number of prime numbers less than a non-negative number, n. Example: Input: 10 Output: 4 E ...

  4. 求素数个数的优化-LeetCode204

    问题 计数质数 统计所有小于非负整数 n 的质数的数量. 示例: 输入: 10 输出: 4 解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 . 第一种解法容易想到但是会 超时 ...

随机推荐

  1. 解决:Android 8.0检测不到当前的activity

    前两天从Android 7.0升级到Android 8.0,今天在用 adb shell dumpsys activity | findstr "mFocusedActivity" ...

  2. 转:Tomcat 7.0配置SSL的问题及解决办法

    原文:https://dong-shuai22-126-com.iteye.com/blog/1830209

  3. 从0开始springboot

    http://412887952-qq-com.iteye.com/blog/2291500

  4. 【LeetCode 222_完全二叉树_遍历】Count Complete Tree Nodes

    解法一:递归 int countNodes(TreeNode* root) { if (root == NULL) ; TreeNode *pLeft = root->left; TreeNod ...

  5. Class.getResource()方法的使用

    我们之前使用路径总是有点不知道怎么用,发现别人使用Class.getResource()方法,好像挺不错的样子.于是看看博客,简单学习下. 参考链接:http://blog.csdn.net/lcj8 ...

  6. L200

    Last week, I read a story about a 34-year-old British woman who is extremely afraid of metal forks.S ...

  7. New Concept English Two 22 58

    $课文56  比声音还快! 579. Once a year, a race is held for old cars. 旧式汽车的比赛每年举行一次. 580. A lot of cars enter ...

  8. c++下为使用pimpl方法的类编写高效的swap函数

    swap函数是c++中一个常用的函数,用于交换两对象的值,此外还用于在重载赋值运算符中处理自赋值情况和进行异常安全性编程(见下篇),标准模板库中swap的典型实现如下: namespace stl { ...

  9. Shell 命令行,写一个自动整理 ~/Downloads/ 文件夹下文件的脚本

    Shell 命令行,写一个自动整理 ~/Downloads/ 文件夹下文件的脚本 在 mac 或者 linux 系统中,我们的浏览器或者其他下载软件下载的文件全部都下载再 ~/Downloads/ 文 ...

  10. Winform开发之SqlCommand常用属性和方法

    SqlCommand类表示要对 SQL Server 数据库执行的一个 Transact-SQL 语句或存储过程,有若干个属性和若干个方法,具体的各类方法使用可以从msdn上找到. 这里介绍几个常用东 ...