Map的应用(节省空间和时间)

来源:互联网 发布:网络渗透软件 编辑:程序博客网 时间:2024/05/01 10:19
package 解析URL;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
public class 优化的阶乘计算 {
     static Map<BigInteger, BigInteger> map=new HashMap<BigInteger, BigInteger>();
    
    public static void main(String[] args){
        map.clear();
        Random random=new Random();
        for(int i=0;i<10;i++)
        {
            int ranInt=random.nextInt(10);
            System.out.println(ranInt);
            System.out.println(fuck(BigInteger.valueOf(ranInt)));
            System.out.println("*****************");
        }
        System.out.println("000000000000000000000000000000000000000");
        athot();
        
    }
    
    private static BigInteger fuck(BigInteger value) {
        if(value.compareTo(BigInteger.valueOf(0))==0){
            return BigInteger.valueOf(1);
        }else{
            //从缓存中查找
            BigInteger  factor=(BigInteger)map.get(value);
            if(factor!=null){
                System.out.println("-------------这个是在集合中取的==============");
                return factor;
            }
                BigInteger nplusOne=value.subtract(BigInteger.valueOf(1));
                factor=fuck(nplusOne).multiply(value);
                map.put(value, factor);
                return factor;
            
        }
        
    }
    
    
    private static void athot() {
        java.util.Iterator<Entry<BigInteger, BigInteger>> iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            @SuppressWarnings("rawtypes")
            Map.Entry entry = (Map.Entry) iter.next();
            
            System.out.println(entry.getKey()+" --> "+entry.getValue());
            //System.out.println(entry.getValue());
        }              
    }
    
}


0 0
原创粉丝点击