Java经典编程题50道之二十七
求100之内的素数。
public class Example27 {
public static void main(String[] args) {
prime();
}
public static void prime() {
System.out.print(2 + "\t");
System.out.print(3 + "\t");
int count = 2;
boolean flag = false;
for (int i = 2; i <= 100; i++) {
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0) {
flag = false;
break;
} else {
flag = true;
}
}
if (flag) {
count++;
System.out.print(i + "\t");
if (count % 10 == 0) {
System.out.println();
}
}
}
System.out.println("\n共有" + count + "个素数。");
}
}