关于这道算法题,我们应该先知道它的考点是什么,才能做好这道题,这道题有两个考点,第一点,考验我们算法的能力,这里的考点是如何判断一个数是素数,有很多方法可以判断,当然越优化,那么我们来看看不算太优化的(这是判断100万以内的,1000万跑太久了,没等到哈哈)
然后看看优化后的,这也是我们最想看到的
这就是其中一个考点,然后一个考点就是多线程的基础了
思路,主体就是把一千万个数平均分配,每个线程判断一个范围,统计这个范围内的素数个数,然后把每个线程统计的数相加即可了,下面是整体代码,首先是判断一个范围内素数的类,然后是多线程代码,最后结果显示一千万以内素数个数
public class NumberCounter implements Runnable{
private int start;
private int end;
private int count;
public NumberCounter(int start,int end) {
this.start = start;
this.end = end;
this.count = 0;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
if(judge(i)){
count++;
}
}
}
private boolean judge(int number) {
if (number <= 1) return false;
for (int i = 2; i <= Math.sqrt(number); i++) {
if(number % i == 0) {
return false;
}
}
return true;
}
public int getCount() {
return count;
}
}
import java.util.ArrayList;
import java.util.List;
public class TestDemo5 {
private static final int N = 10000000; // 范围:1千万以内
public static void main(String[] args) {
long begin = System.currentTimeMillis();
int threadcount = 10;
int step = N/threadcount;
List<NumberCounter> counters = new ArrayList<>(); //把它分段
for (int i = 0; i < threadcount; i++) {
int start = i*step + 1;
int end = (i == threadcount-1) ? N:start+step-1; //如果是创的最后一个,end就等于N
counters.add(new NumberCounter(start,end));
}
List<Thread> threads = new ArrayList<>(); //创建多个线程用线性表连接起来
for (NumberCounter counter:counters) {
Thread thread = new Thread(counter);
threads.add(thread);
thread.start();
}
for (Thread thread:threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int total = 0;
for (NumberCounter counter:counters) {
total += counter.getCount();
}
long end = System.currentTimeMillis();
System.out.println("素数个数:" + total+" 消耗时间"+(end-begin));
}
}