代码示例:
private static void Sushu() {
List<String> sushuList = new ArrayList();
int num = 10;
int j;
boolean isSushu;
for (int i = 2; i <= 10; i++) {
// 备注:这里加上这个判断其实有些时候也不一定会提升性能很明显,加了判断本身也是需要消耗计算机资源。数量比较大,提升会比较明显
if (i == 1 || (i % 2 == 0 && i != 2)) {
continue; // 偶数和1排除
}
isSushu = true;
for (j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0) {
isSushu = false;
break;
}
}
if (isSushu) {
sushuList.add(i + "");
}
}
System.out.println("数量:" + sushuList.size());
System.out.print("元素:");
for (String str : sushuList) {
System.out.print(str + " ");
}
}
运行结果:
数量:4
元素:2 3 5 7
进程已结束,退出代码0