Smallest pair of indices with product of subarray co | Function to calculate GCD of two letegers ; Recursively calculate GCD ; Function to find the lexicographically smallest pair of indices whose product is co - prime with the product of the subarrays on its left and right ; Stores the suffix product of array elements ; Set 0 / 1 if pair satisfies the given condition or not ; Initialize array right_prod [ ] ; Update the suffix product ; Stores product of all elements ; Stores the product of subarray in between the pair of indices ; Iterate through every pair of indices ( i , j ) ; Store product of A [ i , j ] ; Check if product is co - prime to product of either the left or right subarrays ; If no such pair is found , then prlet - 1 ; Driver code ; Function Call
function gcd ( a , b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } function findPair ( A , N ) { let right_prod = [ ] ; let flag = 0 ; right_prod [ N - 1 ] = A [ N - 1 ] ; for ( let i = N - 2 ; i >= 0 ; i -- ) right_prod [ i ] = right_prod [ i + 1 ] * A [ i ] ; let total_prod = right_prod [ 0 ] ; let product ; for ( let i = 1 ; i < N - 1 ; i ++ ) { product = 1 ; for ( let j = i ; j < N - 1 ; j ++ ) { product *= A [ j ] ; if ( gcd ( product , right_prod [ j + 1 ] ) == 1 || gcd ( product , total_prod / right_prod [ i ] ) == 1 ) { flag = 1 ; document . write ( " " + ( i - 1 ) + " " + ( j + 1 ) + " " ) ; break ; } } if ( flag == 1 ) break ; } if ( flag == 0 ) document . write ( - 1 ) ; } let arr = [ 2 , 4 , 1 , 3 , 7 ] ; let N = arr . length ; findPair ( arr , N ) ;