给出1个整数n
返回 1个质因数数组, 数据内的元素都是大于1都质数, 而且数据内的元素的乘积就是给出的整数n
例如 n = 100, 返回[2,2,5,5]
思路, 基本上就是硬来。
当然如果可以先求出小与n点质数列表。 问题会简单得多, 但是求出这质数列表是另1个story, 这里不会采用这种方法。
我们 会 从x=2开始, 逐个去除n,如果n能被x整除, 则把x放入1个结果列表,而且n=n/x
然后继续用x去除 n (上一次操作的商),直至n不能不x整除时, x=x+1
继续此操作, 直至n=1(分解完成)为止。
代码:
/**
* 质因数分解
*/
public class PrimeFactorization {
public static void main(String[] args) {
PrimeFactorizationUitl pf = new PrimeFactorizationUitl();
System.out.println(MessageFormat.format("The prime factorization of {0} is {1} ", 5, pf.getResultList(5)));
System.out.println(MessageFormat.format("The prime factorization of {0} is {1} ", 10, pf.getResultList(10)));
System.out.println(MessageFormat.format("The prime factorization of {0} is {1} ", 100, pf.getResultList(100)));
System.out.println(MessageFormat.format("The prime factorization of {0} is {1} ", 89, pf.getResultList(89)));
System.out.println(MessageFormat.format("The prime factorization of {0} is {1} ", 90, pf.getResultList(90)));
}
}
class PrimeFactorizationUitl{
private List<Integer> primeList = new ArrayList<>();
public List<Integer> getResultList(int n){
if (n < 2){
throw new RuntimeException("n cannot be smaller than 2");
}
this.primeList.clear();
/*
* Just need to try from 1 to n/2
*/
int checkMax = n/2;
for (int i=2; i<=checkMax; ){
if (1==n){
/*
n has been decomposed by prime factors
*/
break;
}
if (0==n%i){
n = n/i;
this.primeList.add(i);
/**
* Keep the value of i unchanged and enter the next loop
*/
continue;
}
i++;
}
/*
* n is a prime number
*/
if (0 == this.primeList.size()){
this.primeList.add(n);
}
return this.primeList;
}
}