BigInteger 判断素数。。
又是在问问上看到。。这次的题目是:
编写一个程序,用一个线程显示时间,一个线程用来计算(如判断一个大数是否是质数),当质数计算完毕后,停止显示时间。
于是先用BigInteger的isProbablePrime判断是否可能是素数,然后再进行精确计算(就是从2到sqrt(n) 囧),copy了别人的一个BigInteger sqrt函数~
-
import java.text.SimpleDateFormat;
-
import java.math.BigInteger;
-
import java.util.Date;
-
-
public class Main
-
{
-
{
-
TimeThread tThread = new TimeThread();
-
CountThread cThread = new CountThread(n, tThread);
-
-
cThread.start();
-
}
-
}
-
-
{
-
-
private BigInteger number;
-
private TimeThread thread;
-
-
this.thread = thread;
-
this.number = number;
-
}
-
-
BigInteger h = a;
-
while (l.compareTo(h)<0) {
-
int tmp = m.pow(2).compareTo(a);
-
if (tmp == 0) {
-
return m;
-
}
-
else
-
}
-
return l;
-
}
-
-
public void run() {
-
thread.start();
-
if(number.isProbablePrime(5)) {
-
// 如果这个数有95%的概率是质数 再进行精确判断
-
{
-
break;
-
}
-
}
-
}
-
thread.stopflag();
-
System.out.println("[Result] " + number + " is " + (i.compareTo(e) <= 0 ? "not ":"") + "a prime !");
-
System.out.println("Time start in " + format.format(thread.getStartTime()) + ", end in " + format.format(thread.getEndTime()) + ".");
-
}
-
}
-
-
{
-
-
private boolean runFlag = true;
-
-
private Date startDate;
-
-
private Date endDate;
-
-
public void start() {
-
super.start();
-
}
-
-
return startDate;
-
}
-
-
return endDate;
-
}
-
-
public void stopflag() {
-
runFlag = false;
-
}
-
-
public void run() {
-
while(runFlag) {
-
}
-
}
-
}
运行截图:
- 无匹配