java实现查找101到200间的素数
目录
java实现查找101到200间的素数
以两种不同的方法使用java实现查找101到200间的素数。
方法一:
循环遍历101到200,对于每一次遍历都执行,除以2到该数平方根的取余。
方法二:
先找到2到最大值的平方根的倍数,即合数,再剔除掉。
循环遍历101到200的平方根14,对于每一次遍历都执行获取当前值得倍数(从101除以当前值开始),并从列表里将其remove掉。
package test;
import java.util.ArrayList;
/**
* 101-200之间有多少个素数
*/
import java.util.List;
public class test2 {
//方法一
public List<Integer> getSushu1(int min,int max) {
List<Integer> sushus = new ArrayList<>();
int count = 0;
for (int i = min; i <= max;i++) {
int j;
for (j = 2; j < Math.sqrt(i); j++) {
count += 1;
if (i % j == 0) {
break;
}
}
if (j > Math.sqrt(i)) {
sushus.add(i);
}
}
System.out.println(count);
return sushus;
}
//方法二
public List<Integer> getSushu2(int min,int max) {
List<Integer> sushus = new ArrayList<>();
for(int i = min;i <= max;i++) {
sushus.add(i);
}
int count = 0;
for (int i = 2; i <= Math.sqrt(max);i++) {
for(int j = min/i;j<=max/i;j++) {
count += 1;
if(sushus.contains(i * j)) {
sushus.remove(sushus.indexOf(i* j));
}
}
}
System.out.println(count);
return sushus;
}
public static void main(String[] args) {
test2 test2 = new test2();
System.out.println(test2.getSushu1(101,200));
System.out.println(test2.getSushu2(101,200));
}
}