Count of elements which are power of 2 in a given range subarray for Q queries | Java implementation to find elements that are a power of two ; prefix [ i ] is going to store the number of elements which are a power of two till i ( including i ) . ; Function to find the maximum range whose sum is divisible by M . ; Calculate the prefix sum ; Function to return the number of elements which are a power of two in a subarray ; Driver code
import java . util . * ; class GFG { static final int MAX = 10000 ; static int [ ] prefix = new int [ MAX + 1 ] ; static boolean isPowerOfTwo ( int x ) { if ( x != 0 && ( ( x & ( x - 1 ) ) == 0 ) ) return true ; return false ; } static void computePrefix ( int n , int a [ ] ) { if ( isPowerOfTwo ( a [ 0 ] ) ) prefix [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { prefix [ i ] = prefix [ i - 1 ] ; if ( isPowerOfTwo ( a [ i ] ) ) prefix [ i ] ++ ; } } static int query ( int L , int R ) { if ( L == 0 ) return prefix [ R ] ; return prefix [ R ] - prefix [ L - 1 ] ; } public static void main ( String [ ] args ) { int A [ ] = { 3 , 8 , 5 , 2 , 5 , 10 } ; int N = A . length ; int Q = 2 ; computePrefix ( N , A ) ; System . out . println ( query ( 0 , 4 ) ) ; System . out . println ( query ( 3 , 5 ) ) ; } }