Queries to calculate sum of array elements consisting of odd number of divisors | Python3 program for the above approach ; 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
from math import sqrt NEW_LINE def OddDivisorsSum ( n , q , a , Query ) : NEW_LINE INDENT DP = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = sqrt ( a [ i ] ) NEW_LINE if ( x * x == a [ i ] ) : NEW_LINE INDENT DP [ i ] = a [ i ] NEW_LINE DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT DP [ i ] = DP [ i - 1 ] + DP [ i ] NEW_LINE DEDENT for i in range ( q ) : NEW_LINE INDENT l = Query [ i ] [ 0 ] NEW_LINE r = Query [ i ] [ 1 ] NEW_LINE if ( l == 0 ) : NEW_LINE INDENT print ( DP [ r ] , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( DP [ r ] - DP [ l - 1 ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 5 , 6 , 9 ] NEW_LINE N = len ( arr ) NEW_LINE Q = 3 NEW_LINE Query = [ [ 0 , 2 ] , [ 1 , 3 ] , [ 1 , 4 ] ] NEW_LINE OddDivisorsSum ( N , Q , arr , Query ) NEW_LINE DEDENT