Count of quadruplets from range [ L , R ] having GCD equal to K | Function to return the gcd of a and b ; Function to return the count of quadruplets having gcd = k ; Count the frequency of every possible gcd value in the range ; To store the required count ; Calculate the answer using frequency values ; Return the required count ; Driver code
function gcd ( a , b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } function countQuadruplets ( l , r , k ) { let frequency = new Array ( r + 1 ) ; frequency . fill ( 0 ) ; for ( let i = l ; i <= r ; i ++ ) { for ( let j = l ; j <= r ; j ++ ) { frequency [ gcd ( i , j ) ] ++ ; } } let answer = 0 ; for ( let i = 1 ; i <= r ; i ++ ) { for ( let j = 1 ; j <= r ; j ++ ) { if ( gcd ( i , j ) == k ) { answer += ( frequency [ i ] * frequency [ j ] ) ; } } } return answer ; } let l = 1 , r = 10 , k = 2 ; document . write ( countQuadruplets ( l , r , k ) ) ;