我是看了别人的博客,3s内使用python找到一亿内的质数,第一反应是挺厉害啊,一个一个判断肯定超时啊,那是有啥高招?然后准备学习学习,然而,python能力太渣,没看懂(主要是没耐心看)。
那我能不能使用java试试呢,按照我的想法,试了试,2s内。
代码:
public class TestZhiNum {
public static void main(String[] args) {
long start = System.currentTimeMillis();
System.out.println(getZhiNum(100000000));
System.out.println(System.currentTimeMillis() - start);
}
private static int getZhiNum(int num) {
//是否是合数
boolean[] b = new boolean[num + 1];
int ans = 0;
for (int i = 2; i <= num; i++) {
if (!b[i]) {
ans++;
for (int j = i; j <= num / i; j++) {
//这一步还是会有重复的,但是已经少很多了
b[j * i] = true;
}
}
}
return ans;
}
}