書中添加了2個計數(shù)器
一個是命中計數(shù)器里伯,一個是緩存命中計數(shù)器(如果新的參數(shù)和上次一樣吓揪,則直接獲燃嘣鳌)
private BigInteger lastNumber;//上次的因子
private BigInteger[] lastFactors;//上次的因式分解的結(jié)果
private long hits;//訪問次數(shù)
private long cacheHits;//緩存命中次數(shù)
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){
//可變的 共享變量(計數(shù)器)寫入 需要考慮并發(fā)
//而且分解過程和記錄計數(shù)器過程不干擾 可以拆分
++hits;//記錄
if(x.equals(lastNumber)){
++cacheHits;
factors = lastFactors.clone();//緩存上次結(jié)果
}
}
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) {
//因數(shù)分解過程
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;
}