Queries to calculate sum of array elements consisting of odd number of divisors | Function to get the middle index from the given ranges ; Recursive function to find the sum of values in the given range of the array ; If segment of this node is a part of given range , then return the sum of the segment ; If segment of this node is outside the given range ; If a part of this segment overlaps the given range ; Function to find the sum of elements in the range from index qs ( query start ) to qe ( query end ) ; Invalid ranges ; Recursive function to construct the Segment Tree for array [ ss . . se ] . si is index of current node in tree st ; If there is one element in the array ; Recur for left and right subtrees and store the sum of values in this node ; Function to construct segment tree from the given array ; Allocate memory for the segment tree Height of segment tree ; Maximum size of segment tree ; Allocate memory ; Fill the allocated memory st ; Return the constructed segment tree ; Function to find the sum of elements having odd number of divisors in index range [ L , R ] for Q queries ; Traverse the array , arr [ ] ; Replace elements that are not perfect squares with 0 ; Build segment tree from the given array ; Iterate through all the queries ; Print sum of values in array from index l to r ; Driver Code
function getMid ( s , e ) { return s + Math . floor ( ( e - s ) / 2 ) ; } function getSumUtil ( st , ss , se , qs , qe , si ) { if ( qs <= ss && qe >= se ) return st [ si ] ; if ( se < qs ss > qe ) return 0 ; let mid = getMid ( ss , se ) ; return getSumUtil ( st , ss , mid , qs , qe , 2 * si + 1 ) + getSumUtil ( st , mid + 1 , se , qs , qe , 2 * si + 2 ) ; } function getSum ( st , n , qs , qe ) { if ( qs < 0 qe > n - 1 qs > qe ) { document . write ( " " ) ; return - 1 ; } return getSumUtil ( st , 0 , n - 1 , qs , qe , 0 ) ; } function constructSTUtil ( arr , ss , se , st , si ) { if ( ss == se ) { st [ si ] = arr [ ss ] ; return arr [ ss ] ; } let mid = getMid ( ss , se ) ; st [ si ] = constructSTUtil ( arr , ss , mid , st , si * 2 + 1 ) + constructSTUtil ( arr , mid + 1 , se , st , si * 2 + 2 ) ; return st [ si ] ; } function constructST ( arr , n ) { let x = ( Math . ceil ( Math . log ( n ) / Math . log ( 2 ) ) ) ; let max_size = 2 * Math . pow ( 2 , x ) - 1 ; let st = new Array ( max_size ) ; constructSTUtil ( arr , 0 , n - 1 , st , 0 ) ; return st ; } function OddDivisorsSum ( n , q , arr , Query ) { for ( let i = 0 ; i < n ; i ++ ) { let sq = Math . sqrt ( arr [ i ] ) ; if ( sq * sq != arr [ i ] ) arr [ i ] = 0 ; } let st = constructST ( arr , n ) ; for ( let i = 0 ; i < q ; i ++ ) { let l = Query [ i ] [ 0 ] ; let r = Query [ i ] [ 1 ] ; document . write ( getSum ( st , n , l , r ) + " " ) ; } } let arr = [ 2 , 4 , 5 , 6 , 9 ] ; let N = arr . length ; let Q = 3 ; let Query = [ [ 0 , 2 ] , [ 1 , 3 ] , [ 1 , 4 ] ] ; OddDivisorsSum ( N , Q , arr , Query ) ;