0
点赞
收藏
分享

微信扫一扫

每日一练防手生

得一道人 2022-01-31 阅读 11
java

将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。

public class PrimeFactorDemo {
    private final static int START_FACTOR = 2;

    public void printPrimeFactor(int i) {
        int factor = START_FACTOR;
        System.out.print(i + "=");
        int leftNum = i;
        while (factor <= Math.sqrt(leftNum)) {
            if (leftNum % factor == 0) {
                leftNum = leftNum / factor;
                System.out.print(factor + "*");
                factor = START_FACTOR;
                continue;
            } else {
                factor++;
            }
        }
        if (leftNum < i) {
            System.out.print(leftNum);
        } else {
            System.out.println("不可分解质因数");
        }
    }

    public static void main(String[] args) {
        PrimeFactorDemo demo = new PrimeFactorDemo();
        demo.printPrimeFactor(90);
    }
}

举报

相关推荐

0 条评论