package cn.yjnull.datastrhomework;
/** * 编写一个程序来确定正整数N是否是素数 * @author Yjnull * */
public class DataStr2_20 {
public static boolean isPrime(int n){
if(2==n) return true;
if(n<=1||0==n%2){
return false;
}else{
for(int i = 3;i<=Math.sqrt(n);i+=2){
if(n%i==0){
return false;
}
}
return true;
}
}
public static void isEeatosthese(int n){
int a[] = new int[n];
int count=0;
for (int i = 2; i < n; i++)
a[i] = 1;
for (int i = 2; i < Math.sqrt(n); i++) {
if(1==a[i])
for (int j = i+i; j < n; j+=i) {
a[j]=0;
}
}
for (int i = 2; i < n; i++) {
if(1==a[i])
count++;
}
System.out.println(count);
}
public static void main(String[] args) {
int s=0;
double time = System.currentTimeMillis();
for (int i = 1; i <= 10000000; i++) {
if(isPrime(i)){
s++;
}
}
double time2 = System.currentTimeMillis();
System.out.println(s+"\n"+(time2-time)+"ms");
double time3 = System.currentTimeMillis();
isEeatosthese(10000000);
double time4 = System.currentTimeMillis();
System.out.println("\n"+(time4-time3)+"ms");
}
}