Check if Decimal representation of given Binary String is divisible by K or not | Function to check the binary number is divisible by K ; Array poweroftwo will store pow ( 2 , i ) % k ; Initializing the first element in Array ; Storing every pow ( 2 , i ) % k value in the array ; To store the remaining ; Iterating till N ; If current bit is 1 ; Updating rem ; If completely divisible ; If not Completely divisible ; Driver Code ; Given Input ; length of string s ; Function Call
def divisibleByk ( s , n , k ) : NEW_LINE INDENT poweroftwo = [ 0 for i in range ( n ) ] NEW_LINE poweroftwo [ 0 ] = 1 % k NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT poweroftwo [ i ] = ( poweroftwo [ i - 1 ] * ( 2 % k ) ) % k NEW_LINE DEDENT rem = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ n - i - 1 ] == '1' ) : NEW_LINE INDENT rem += ( poweroftwo [ i ] ) NEW_LINE rem %= k NEW_LINE DEDENT DEDENT if ( rem == 0 ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT else : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "1010001" NEW_LINE k = 9 NEW_LINE n = len ( s ) NEW_LINE print ( divisibleByk ( s , n , k ) ) NEW_LINE DEDENT