0

This is the code for evaluating factors of given integer array. The problem is I need to find LCM from the list I have received as output. Suggest something for removing duplicate elements from list

Main method

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int [] ar = {6,12,36};
        for (int a:
             ar) {
            System.out.println(getFactor(a));
        }

getFactor(long) returns the list of factors

private static List<Integer> getFactor(long n) {
        List<Integer> l = new ArrayList<>();
        for (int i=2;n!=1;i++)
        {
            if(n%i==0)
            {
                l.add(i);
                n=n/i;
                i=1;
            }
        }
        return l;
    }

/*Input
6,12,36
Output
[2, 3]
[2, 2, 3]
[2, 2, 3, 3]*/

Problem remove the [2,3] duplicates from other lists to get LCM(Least Common Multiple).

divine_rythm
  • 149
  • 3
  • 9
  • 1
    Well seeing as you are removing elements to get LCM why not calculate LCM directly from given input? `LCM(a,b) = a*b/GCD(a,b)` and GCD can easilly be found with Euclid algorithm, Java even has GCD implementation in it's BigInteger library `BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).intValue()` – Photon Feb 22 '20 at 09:45
  • You arrays are sorted. You can use it to eliminate duplicates with simple for loops – Damien Feb 22 '20 at 12:53

2 Answers2

1

No where in your code you're calculating the lcm. All I see is you have found the factors of three numbers.

[2, 3]   -> Factors of 6
[2, 2, 3] -> Factors of 12
[2, 2, 3, 3] -> -> Factors of 6

You'll have to write another function to calculate the lcm.

  • I know the recursive approach for gcd(x,y) and after that we evaluate lcm. I was just wondering if we can find lcm by evaluating the factors and eliminating the common ones – divine_rythm Feb 23 '20 at 11:47
1

Suggest something for removing duplicate elements from list

Use Set instead of a List

private static Set<Integer> getFactor(long n) {
    Set<Integer> l = new HashSet<>();
    for (int i = 2; n != 1; i++) {
        if (n % i == 0) {
            l.add(i);
            n = n / i;
            i = 1;
        }
    }
    return l;
}

Output:

[2, 3]
[2, 3]
[2, 3]

Recommended reading: What is the difference between Set and List?

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • Thanks for the solution, but it didn't work in my case so what I did was picking the shortest length then multiply all the elements till it exists in other lists, and that worked for me. – divine_rythm May 25 '20 at 12:17