text: Number of subarrays with GCD equal to 1 | Javascript implementation of the approach ; Function to return the required count ; To store the final answer ; To store the GCD starting from index ' i ' ; Loop to find the gcd of each subarray from arr [ i ] to arr [ i ... n - 1 ] ; Increment the count if curr_gcd = 1 ; Return the final answer ; Driver code
code: function __gcd ( a , b ) { if ( b == 0 ) return a ; return __gcd ( b , a % b ) ; } function cntSubArr ( arr , n ) { var ans = 0 ; for ( var i = 0 ; i < n ; i ++ ) { var curr_gcd = 0 ; for ( var j = i ; j < n ; j ++ ) { curr_gcd = __gcd ( curr_gcd , arr [ j ] ) ; ans += ( curr_gcd == 1 ) ; } } return ans ; } var arr = [ 1 , 1 , 1 ] ; var n = arr . length ; document . write ( cntSubArr ( arr , n ) ) ;