Count subarrays having product equal to the power of a given Prime Number | Python 3 program for the 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
from math import log NEW_LINE def isPower ( m , y ) : NEW_LINE INDENT res1 = log ( y ) // log ( m ) NEW_LINE res2 = log ( y ) // log ( m ) NEW_LINE return ( res1 == res2 ) NEW_LINE DEDENT def numSub ( arr , n , m ) : NEW_LINE INDENT ans = 0 NEW_LINE cnt = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( isPower ( m , arr [ i ] ) ) : NEW_LINE INDENT cnt += 1 NEW_LINE ans += ( cnt * ( cnt - 1 ) ) // 2 NEW_LINE DEDENT else : NEW_LINE INDENT cnt = 0 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 1 , 3 ] NEW_LINE m = 3 NEW_LINE n = len ( arr ) NEW_LINE print ( numSub ( arr , n , m ) ) NEW_LINE DEDENT