Queries to calculate sum of array elements consisting of odd number of divisors | package whatever do not write package name here ; Function to find the sum of elements having odd number of divisors in index range [ L , R ] for Q queries ; Initialize the dp [ ] array ; Traverse the array , arr [ ] ; If a [ i ] is a perfect square , then update value of DP [ i ] to a [ i ] ; Find the prefix sum of DP [ ] array ; Iterate through all the queries ; Find the sum for each query ; Driver Code
import java . io . * ; class GFG { static void OddDivisorsSum ( int n , int q , int [ ] a , int [ ] [ ] Query ) { int [ ] DP = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { int x = ( int ) ( Math . sqrt ( a [ i ] ) ) ; if ( x * x == a [ i ] ) DP [ i ] = a [ i ] ; } for ( int i = 1 ; i < n ; i ++ ) { DP [ i ] = DP [ i - 1 ] + DP [ i ] ; } for ( int i = 0 ; i < q ; i ++ ) { int l = Query [ i ] [ 0 ] ; int r = Query [ i ] [ 1 ] ; if ( l == 0 ) { System . out . print ( DP [ r ] + " ▁ " ) ; } else { System . out . print ( DP [ r ] - DP [ l - 1 ] + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 4 , 5 , 6 , 9 } ; int N = arr . length ; int Q = 3 ; int [ ] [ ] Query = { { 0 , 2 } , { 1 , 3 } , { 1 , 4 } } ; OddDivisorsSum ( N , Q , arr , Query ) ; } }