当前位置: 首页 > news >正文

找质数(枚举 埃氏筛 线性筛)

输入一个数,返回小于等于这个数的质数。

枚举法:

    public static int countPrimes(int n) {int cnt=0;for(int i=2;i<n;i++) {if(prime(i))cnt++;}return cnt;}private static boolean prime(int x) {for(int i=2;i*i<=x;i++){if(x%i==0)return false;}return true;}

埃式筛法: 

class Solution {public static int countPrimes(int n) {int cnt = 0;int arr[] = new int[n + 1];Arrays.fill(arr, 1);for (int i = 2; i < n; i++) {if (arr[i] == 1) cnt++;if ((long) i * i < n) {for (int j = 2 * i; j <= n; j += i) arr[j] = 0;}}return cnt;}
}

线性筛法:

class Solution {public static void main(String[] args) {System.out.println(countPrimes(10));}public static int countPrimes(int n) {int cnt = 0;boolean arr[] = new boolean[n + 1];for (int i = 2; i < n; i++) {if (!arr[i]) cnt++;for (int j = 2 * i; j <= n; j += i) arr[j] = true;}return cnt;}
}
http://www.lryc.cn/news/214876.html

相关文章:

  • 第十二章 ObjectScript 系统标志和限定符 (qspec) - 标志
  • 解决Windows Server 2012 由于没有远程桌面授权服务器可以提供需求可证
  • 上位机底部栏 UI如何设置
  • MySQL表的增删改查(基础)
  • uniapp书写顶部选项卡代码详细例子
  • 注册中心ZK、nameServer、eureka、Nacos介绍与对比
  • 杂志详情。
  • 前端知识与基础应用#2
  • 【3D 图像分割】基于 Pytorch 的 VNet 3D 图像分割6(数据预处理)
  • 硬件加速器及其深度神经网络模型的性能指标理解
  • 嵌入式每日500(4)231104 (Flash类型定义、Flash常量定义、Flash函数)
  • 21款奔驰GLC300L升级23P驾驶辅助 出行更加的安全
  • 【小黑嵌入式系统第七课】PSoC® 5LP 开发套件(CY8CKIT-050B )——PSoC® 5LP主芯片、I/O系统、GPIO控制LED流水灯的实现
  • 深度学习简史
  • CSRF 和 XSS 是什么
  • 亚信科技发布“电信级”核心交易数据库AntDB7.0,助力政企“信”创未来!
  • 硬件调试-电源纹波测量
  • 【洛谷算法题】P5710-数的性质【入门2分支结构】
  • arcgis图上添加发光效果!
  • [MySQL]——SQL预编译、动态sql
  • 安装ifconfig命令(两步搞定)
  • 【蓝桥杯 第十届省赛Java B组】真题训练(A - H)H待更新
  • 【牛客题】二进制求和 <模拟>
  • Error:Only idle or expired IP address can be disabled.
  • Xubuntu16.04系统中create_ap开启5G网络的踩坑记录
  • 8. 一文快速学懂常用工具——Linux命令(上)
  • @RestController注解说明
  • Excel中行列范围的转换
  • golang的类型断言
  • 监听dom变化,监听dom属性变化