Count subarrays having product equal to the power of a given Prime Number | Java code of above approach ; Function to check if y is a power of m or not ; Calculate log y base m and store it in a variable with integer datatype ; Calculate log y base m and store it in a variable with double datatype ; If res1 and res2 are equal , return True . Otherwise , return false ; Function to count the number of subarrays having product of elements equal to a power of m , where m is a prime number ; Stores the count of subarrays required ; Stores current sequence of consecutive array elements which are a multiple of m ; Traverse the array ; If arr [ i ] is a power of M ; Increment cnt ; Update ans ; Update cnt ; Return the count of subarrays ; Driver code ; Input
import java . util . * ; class GFG { static boolean isPower ( int m , int y ) { int res1 = ( int ) Math . log ( y ) / ( int ) Math . log ( m ) ; double res2 = ( int ) Math . log ( y ) / ( int ) Math . log ( m ) ; return ( res1 == res2 ) ; } static int numSub ( int arr [ ] , int n , int m ) { int ans = 0 ; int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isPower ( m , arr [ i ] ) ) { cnt ++ ; ans += ( cnt * ( cnt - 1 ) ) / 2 ; } else { cnt = 0 ; } } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 1 , 3 } ; int m = 3 ; int n = arr . length ; System . out . println ( numSub ( arr , n , m ) ) ; } }