Reputation: 2886
Problem: Print all unique combination of factors (except 1) of a given number.
For example:
Input: 12
Output: [[2, 2, 3], [2, 6], [3, 4]]
My Solution:
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);
}
}
Output:
[2, 2, 3, 3, 3, 4, 4, 6, 12]
As per my code, it prints out all the possible factors of 12. The j
loop iterates until the (number/i)
. I create a list of list type ArrayList
called combination
to create a list of lists, but I don't know how to utilize it. Where should I change my code?
Upvotes: 1
Views: 212
Reputation: 2268
I came up with the following method for finding the unique factors of a number. It is a bit more complex, though, than what you had previously tried and there might be a better solution, but the method seems to work correctly.
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));
}
}
}
Output:
[2, 2, 3]
[3, 4]
[2, 6]
[1, 12]
Hopefully this post helps in some way.
Upvotes: 1