'find the gcd of lcm of every pair in an array

You are given an array A consisting of N number and an empty set S. For each pair of numbers A[i] and A[j] in the array (i < j), you need to find their LCM and insert the LCM into the set S.

You need to report the GCD of the elements in set S. Input The first line of the input contains an integer N. The second line of the input contains N space separated integers A[1], A[2],. , A[N].

Constraints

2 <= N <= 100000

1 <= A[i] <= 200000

Output

Output a single integer, the GCD of LCM set S.

import java.io.*;
import java.util.*; 

class Main {
    public static long gcd(long a,long b){
        if(a==0){
            return b;
        }
        if(b==0){
            return a;
        }
        if(a>b){
            return gcd(a%b,b);
        }
        return gcd(a,b%a);
    }
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int arr[]=new int[n];
        int min=Integer.MAX_VALUE;
        int max=Integer.MIN_VALUE;
        int index1=0,index2=0;
        for(int i=0;i<n;i++){
            arr[i]=sc.nextInt();
            if(arr[i]<min){
                min=arr[i];
                index1=i;
            }
            if(arr[i]>max){
                max=arr[i];
                index2=i;
            }
        }
        Set<Long> st=new HashSet<Long>();
        List<Long> l=new ArrayList<>();
        for(int i=0;i<n;i++){
            for(int j=i+1;j<n;j++){
                long product=arr[i]*arr[j];
                long hcf=gcd(arr[i],arr[j]);
                if(st.contains(product/hcf)==false){
                    st.add(product/hcf);
                    l.add(product/hcf);
                }
            }
        }
        long sum=l.get(0);
        for(int i=1;i<l.size();i++){
            sum=gcd(sum,l.get(i));
        }
        System.out.println(sum);        
                      // Your code here
    }
}

but i am getting tle with this approach.Can anybody suggest me better approach?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source