java求素数

时间:2024-08-27 10:36:08
  • 按定义

即除了1和它本身以外不再被其他的除数整数

public static void main(String[] args) {
for (int i = 2; i < 100; i++) {
for (int j = 2; j <= i; j++) {
if (i==j) {
System.out.println(i);
}else if (i%j==0) {
break;
}
}
}
}
  • 埃氏筛法

先去掉2的倍数,再去掉3的倍数,再去掉5的倍数,……依此类推,把不大√n的所有素数的倍数剔除,最后剩下的就是素数。代码参考自https://www.cnblogs.com/lsucre/p/6599406.html

public static void main(String[] args) {
//赋值
int num = 100;
boolean[] judge = new boolean[num];
//judge[0] = false;
//judge[1] = false;
for (int i = 2; i < judge.length; i++) {
judge[i] = true;
}
//埃氏筛法
for (int i = 2; i < Math.sqrt(num); i++) {
if (judge[i] == true) {
for (int j = i; j*i < num; j++) {
judge[j*i] = false;
}
}
}
//输出
for (int i = 2; i < num; i++) {
if (judge[i] == true) {
System.out.println(i);
}
}
}