您的位置:首页 > 编程语言 > Go语言

prime counting/质数计算

2012-11-07 12:57 246 查看
public class Prime {

public int getPrime(int num){
boolean isprime[] = new boolean[num+1];
int count =0 ;
for(int i=0; i<num+1; i++){
isprime[i] = true;
}
for(int i=2; i*i< num+1; i++){
if(isprime[i] == true){
for(int j=i; j*i<num+1; j++){
isprime[j*i] = false;
}
}
}
for(int i=2; i<num+1; i++){
if(isprime[i] == true) count++;
}
return count;
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(new Prime().getPrime(1000)); //should be 168
}

}


思路:

   通过不断将质数的整数倍得到的结果标记为非质数来实现。这里使用了 Sieve of Eratosthenes
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm