使用Java找出独特的因素

时间:2018-12-28 19:32:01

标签: java algorithm arraylist

问题: 打印给定数字的所有唯一因子组合(除了1)。

例如: Input: 12

输出:[[2, 2, 3], [2, 6], [3, 4]]

我的解决方案:

public class Unique_factor {
    public static void main(String args[]) {
        int number = 12;
        ArrayList<ArrayList<Integer>> combination = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> abc = new ArrayList<>();
        for(int i = 2; i <= number; i++) {
            if(number % i == 0) {
                abc.add(i);
                int result = number;
                for(int j = i; j <= (number/i); j++) {
                    if(result % j == 0) {
                        result = result / j;
                        abc.add(j);
                    }
                }
            }
        }

        //System.out.println(combination);
        System.out.println(abc);
    }
}

输出:

[2, 2, 3, 3, 3, 4, 4, 6, 12]

根据我的代码,它打印出所有可能的因子12。j循环迭代直到(number/i)。我创建了名为ArrayList的列表类型combination的列表,以创建列表列表,但是我不知道如何利用它。我应该在哪里更改代码?

1 个答案:

答案 0 :(得分:1)

我想出了以下方法来找到数字的独特因素。但是,它比您以前尝试的要复杂一些,可能会有更好的解决方案,但是该方法似乎可以正常工作。

public class UniqueFactors {
    public static void main(String[] args) {
        int input = 12; // Currently, the output is blank if the input is 1
        ArrayList<ArrayList<Integer>> combinations = new ArrayList<>();

        for (int i = 2; i <= input; i++) {
            int result;
            if (input % i == 0) {
                result = input / i;
                ArrayList<Integer> factorSet = new ArrayList<>();
                factorSet.add(i);
                boolean moreFactors = false;
                int result2 = result;
                for (int j = 2; j <= result2; j++) {
                    if (result2 % j == 0) {
                        moreFactors = true;
                        factorSet.add(j);
                        result2 = result2 / j;
                        j = 1; // Reset to one because it will be added to on the next iteration
                    }
                }
                if (!moreFactors) factorSet.add(result);
                //> The following chunk just gets rid of duplicate combinations that were in different orders
                boolean copy = false;
                for (int k = 0; k < combinations.size(); k++) {
                    if (combinations.get(k).size() == factorSet.size()) {
                        Collections.sort(combinations.get(k));
                        Collections.sort(factorSet);
                        if (combinations.get(k).equals(factorSet)) {
                            copy = true;
                            break;
                        }
                    }
                }
                if (!copy) combinations.add(factorSet);
            }
        }

        for (int i = 0; i < combinations.size(); i++) {
            System.out.println(combinations.get(i));
        }
    }
}

输出

[2, 2, 3]
[3, 4]
[2, 6]
[1, 12]

希望这篇文章能有所帮助。