Count of elements having odd number of divisors in index range [ L , R ] for Q queries | C ++ program for the above approach ; Function count the number of elements having odd number of divisors ; Initialise dp [ ] array ; Precomputation ; Find the Prefix Sum ; Iterate for each query ; Find the answer for each query ; Driver Code ; Given array arr [ ] ; Given Query ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void OddDivisorsCount ( int n , int q , int a [ ] , vector < pair < int , int > > Query ) { int DP [ n ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { int x = sqrt ( a [ i ] ) ; if ( x * x == a [ i ] ) DP [ i ] = 1 ; } for ( int i = 1 ; i < n ; i ++ ) { DP [ i ] = DP [ i - 1 ] + DP [ i ] ; } int l , r ; for ( int i = 0 ; i < q ; i ++ ) { l = Query [ i ] . first ; r = Query [ i ] . second ; if ( l == 0 ) { cout << DP [ r ] << endl ; } else { cout << DP [ r ] - DP [ l - 1 ] << endl ; } } } int main ( ) { int N = 5 ; int Q = 3 ; int arr [ ] = { 2 , 4 , 5 , 6 , 9 } ; vector < pair < int , int > > Query Query = { { 0 , 2 } , { 1 , 3 } , { 1 , 4 } } ; OddDivisorsCount ( N , Q , arr , Query ) ; return 0 ; }