书中添加了2个计数器
一个是命中计数器,一个是缓存命中计数器(如果新的参数和上次一样,则直接获取)
private BigInteger lastNumber;//上次的因子
private BigInteger[] lastFactors;//上次的因式分解的结果
private long hits;//访问次数
private long cacheHits;//缓存命中次数
private BigInteger N;//全局变量
public synchronized long getHits(){ return hits; }
public synchronized double getCacheHitRadio(){ return cacheHits / hits; }
public void service(BigInteger x){
BigInteger[] factors = null;
synchronized(this){
//可变的 共享变量(计数器)写入 需要考虑并发
//而且分解过程和记录计数器过程不干扰 可以拆分
++hits;//记录
if(x.equals(lastNumber)){
++cacheHits;
factors = lastFactors.clone();//缓存上次结果
}
}
if(factors == null){
//如果没有本次 x 因式分解的记录 factor即求解过程
factors = factor(x);
synchronized(this){
lastNumber = x;
lastFactors = factors.clone();
}
}
for(BigInteger fac:factors){
System.err.println(fac);
}
}
BigInteger[] factor(BigInteger num) {
//因数分解过程
BigInteger[] factors = new BigInteger[3];
BigInteger min = new BigInteger("2");
int n = 0;
while(num.compareTo(min) == 1){
System.out.println("NUM"+num +" MIN: "+min+"MOD: "+num.mod(min));
if(num.mod(min).compareTo(new BigInteger("0")) == 0){
//num 不被整除且 num>0
factors[n] = min;
n++;
num = num.divide(min);
min = new BigInteger("2");
}else{
min = min.add(new BigInteger("1"));
}
}
if(num.compareTo(min) == 0){
factors[n] = min;
}
return factors;
}
网友评论