50道编程题值04:将一个正整数分解质因数

package com.demo;

import java.util.*;

/**
 * Created by 莫文龙 on 2018/3/26.
 */

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

public class Demo4 {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int num = scanner.nextInt();
        if (num == 1) System.out.print(1);
        int a = num;
        ArrayList list = new ArrayList<>();
        for (int i = 2 ; i <= num ; i ++) {
            if (num % i == 0) {
                list.add(i);
                num = num / i;
                i = 1;
            }
        }
        if (list.size() == 1) {
            System.out.print(1 + "*" + a);
            return;
        }
        for (int i = 0 ; i < list.size() - 1 ; i ++) {
            System.out.print(list.get(i) + "*");
        }
        System.out.println(list.get(list.size() - 1));
    }

}

你可能感兴趣的:(50道Java基础编程练习题)