Calculate the Sum of GCD over all subarrays | Utility function to calculate sum of gcd of all sub - arrays . ; Fixing the starting index of a subarray ; Fixing the ending index of a subarray ; Finding the GCD of this subarray ; Adding this GCD in our sum ; Driver Code
function findGCDSum ( n , a ) { var GCDSum = 0 ; var tempGCD = 0 ; for ( i = 0 ; i < n ; i ++ ) { for ( j = i ; j < n ; j ++ ) { tempGCD = 0 ; for ( k = i ; k <= j ; k ++ ) { tempGCD = __gcd ( tempGCD , a [ k ] ) ; } GCDSum += tempGCD ; } } return GCDSum ; } function __gcd ( a , b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } var n = 5 ; var a = [ 1 , 2 , 3 , 4 , 5 ] ; var totalSum = findGCDSum ( n , a ) ; document . write ( totalSum + " " ) ;