Java 实现:
public class PrintPrime {
public static void main(String[] args) {
printAllPrime(120);
}
public static void printAllPrime(int n) {
boolean[] isPrime = new boolean[n + 1];
for (int i = 1; i <= n; i++) {
isPrime[i] = true;
}
for (int i = 2; i * i <= n; i++) {
if (isPrime[i]) {
for (int j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
for (int i = 1; i < isPrime.length; i++) {
if (isPrime[i])
System.out.print(i + " ");
}
}
}
网友评论