Length of longest subarray with product equal to a power of 2 | C ++ program for the above approach ; Function to check whether a number is power of 2 or not ; Function to find maximum length subarray having product of element as a perfect power of 2 ; Stores current subarray length ; Stores maximum subarray length ; Traverse the given array ; If arr [ i ] is power of 2 ; Increment max_length ; Update max_len_subarray ; Otherwise ; Print the maximum length ; Driver Code ; Given arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPower ( int x ) { return ( x && ( ! ( x & ( x - 1 ) ) ) ) ; } int maximumlength ( int arr [ ] , int N ) { int max_length = 0 ; int max_len_subarray = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( isPower ( arr [ i ] ) == 1 ) { max_length ++ ; max_len_subarray = max ( max_length , max_len_subarray ) ; } else { max_length = 0 ; } } cout << max_len_subarray ; } int main ( ) { int arr [ ] = { 2 , 5 , 4 , 6 , 8 , 8 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maximumlength ( arr , N ) ; return 0 ; }