算法题-质因数分解

给出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;


    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nvd11

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值