vendredi 28 décembre 2018

Find out unique factor using java

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 print out all the possible factor of 12. J loop iterate until the (number/i). I create a list of list type arraylist combination to create a list of list. But don't know how to utilize it? Where should I change my code?

Aucun commentaire:

Enregistrer un commentaire