/*键盘输入一个整形n, 寻找比n小的所有素数*/
import java.io.*;
public class TestSE {
public static void main(String args[]) {
int i=0;
int p=2;
int k=2;
String line = null;
int val = 0;
/* 键盘读取整型赋值给val*/
try {
BufferedReader is = new BufferedReader(
new InputStreamReader(System.in));
line = is.readLine();
val = Integer.parseInt(line);
} catch (NumberFormatException ex) {
System.err.println("Not a valid number: " + line);
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
System.out.println("I read this number: " + val);
/*naive, but it works!*/
int n=val;
int[] a=new int[n];
System.out.println("This is the original numbers:");
for(i=0;i<=n-1;i++){
a[i]=i+1;
System.out.print(a[i]); //输出数组,作为参照
System.out.print(" ");
}
/*算法主要部分,
(1)p初始值为2, 将数组a中所有等于2的倍数的元素(2p,3p,4p...)找出并赋值为0.
(2)之后p++直到a[p-1]!=0, 重复上一步, until p*p>n.
*/
while(p*p<=n){
if(a[p-1]!=0){
k=2;
while(k*p<=n)
{a[k*p-1]=0;
k++;}
p++;
}
else p++;
}
System.out.print("/n");
System.out.println("The primes are:");
for(i=0;i<=n-1;i++){ //输出检测
if(a[i]!=0)
{System.out.print(" ");
System.out.print(a[i]);}
}
}
}
输入20, 运行结果:
20
I read this number: 20
This is the original numbers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
The primes are:
1 2 3 5 7 11 13 17 19