package test; import java.util.*; public class test1 { public static void main(String[] args){ long t1 = System.currentTimeMillis(); System.out.println(factor(100)); System.out.println(factor(18900)); System.out.println(factor(72057554846356433L)); System.out.println(factor(72057554846356487L)); long t2 = System.currentTimeMillis(); System.out.println("耗时:" + (t2-t1)); } public static Map<Long, Integer> factor(long n){ Map<Long,Integer> result = new HashMap<Long,Integer>(); long t = n; //先处理偶数,后面处理时 i步进=2,可以节省一半时间 while (t%2==0){ result.put(2L,result.get(2L)==null ? 1:result.get(2L)+1); t = t/2; } for (long i=3;i<=Math.sqrt(t);){ if (t%i==0){ result.put(i,result.get(i)==null ? 1:result.get(i)+1); t = t/i; }else{ i += 2; } } result.put(t,result.get(t)==null ? 1:result.get(t)+1); t = 1; //return null; return result; } }
1、先把合数分解成2和第二个因数,直到第二个的因数不是偶数,那么分解第二个因数时,步进=2,减少一半判断;
2、分解时,因数小于等于 Math.sqrt(t);
上面代码试验中,比从2开始步进1的方法快一倍(5700ms vs 2700ms);
原文:http://www.cnblogs.com/sicf/p/5209458.html