当前位置:网站首页>【刷题篇】计算质数
【刷题篇】计算质数
2022-07-30 18:50:00 【m0_60631323】
一、题目
OJ链接
给定整数 n ,返回 所有小于非负整数 n 的质数的数量 .
二、题解
思路:将1~n-1上不是素数的数全部除去,剩下的数的数量就是素数
- 除了2,所有的偶数都不是素数,因为4=2x2;6=2x3;8=2x4…
- 在去除掉因子中含有3的所有不是素数的数,
3x2不用再算了,因为计算2x3的时候算过了,所以对于数字i只需从 i x i 开始,3x3=9(不是素数), 3x4不用算(偶数),3x5=15(不是素数)…
public int countPrimes1(int n) {
if(n<3){
return 0;
}
boolean[] f=new boolean[n];
int count =n/2;
for(int i=3;i*i<n;i+=2){
if(f[i]){
//例如i=9时,9在3*3的时候就判断过9不是素数,就已经
//将f[9]=true,而之所以可以跳过9是因为,9*9=3*3*9,
//9*11=3*3*11,就说明,含有9这个因子且不是素数的数,在
//去除以3作为因子所有不是素数的数的时候已经算过了
continue;
}
for(int j=i*i;j<n;j+=2*i){
if(!f[j]){
count--;
f[j]=true;
}
}
}
return count;
}
边栏推荐
- Critical Reviews | A review of the global distribution of antibiotics and resistance genes in farmland soil by Nannong Zou Jianwen's group
- 好未来单季营收2.24亿美元:同比降84% 张邦鑫持股26.3%
- 经济新闻:错误# 15:初始化libiomp5md。dll,但发现libiomp5md。已经初始化dll。解决方法
- LeetCode 练习——关于查找数组元素之和的两道题
- 3D机器视觉厂商的场景争夺战役
- 常见链表题及其 Go 实现
- SwiftUI iOS 精品开源项目之 完整烘焙食品菜谱App基于SQLite(教程含源码)
- MySQL数据类型
- Scrapy框架介绍
- Swiper rotates pictures and plays background music
猜你喜欢
OneFlow source code analysis: Op, Kernel and interpreter
Quickly build an e-commerce platform based on Amazon cloud technology serverless service - performance
ctf.show_web5
The use of @ symbol in MySql
基于inquirer封装一个控制台文件选择器
智慧中控屏
沉浸式体验科大讯飞2022消博会“官方指定产品”
自然语言处理nltk
生物医学论文有何价值 论文中译英怎样翻译效果好
【Pointing to Offer】Pointing to Offer 22. The kth node from the bottom in the linked list
随机推荐
Multiple instances of mysql
《自然语言处理实战入门》---- 文本样本扩展小技巧:使用回译技术进行样本增强
基于b/s架构搭建一个支持多路摄像头的实时处理系统 ---- 使用yolo v5 系列模型
natural language processing nltk
SwiftUI iOS 精品开源项目之 完整烘焙食品菜谱App基于SQLite(教程含源码)
Presto 中 lookUp Join的实现
微信小程序云开发 | 城市信息管理
OneFlow源码解析:Op、Kernel与解释器
MYSQL (Basic) - An article takes you into the wonderful world of MYSQL
kotlin by lazy
C# wpf 无边框窗口添加阴影效果
使用postman调接口报Content type ‘text/plain;charset=UTF-8‘ not supported
【PHPWord】PHPOffice 套件之PHPWord快速入门
【每日一道LeetCode】——191. 位1的个数
(2022杭电多校四)1001-Link with Bracket Sequence II(区间动态规划)
WeChat Mini Program Cloud Development | Urban Information Management
OneFlow source code analysis: Op, Kernel and interpreter
The large-scale application of artificial intelligence AI products in industrial-grade mature shipping ports of CIMC World Lianda will create a new generation of high-efficiency smart ports and innova
C# wpf borderless window add shadow effect
CCNA-网络汇总 超网(CIDR) 路由最长掩码匹配