Make all array elements divisible by a number K | Function to make array divisible ; For each element of array how much number to be subtracted to make it divisible by k ; For each element of array how much number to be added to make it divisible by K ; Calculate minimum difference ; Driver Code
def makeDivisble ( arr , k ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE b1 = [ ] NEW_LINE b2 = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT b1 . append ( arr [ i ] % k ) NEW_LINE DEDENT for j in range ( n ) : NEW_LINE INDENT if ( ( arr [ j ] % k ) != 0 ) : NEW_LINE INDENT b2 . append ( k - ( arr [ j ] % k ) ) NEW_LINE DEDENT else : NEW_LINE INDENT b2 . append ( 0 ) NEW_LINE DEDENT DEDENT c = 0 NEW_LINE mini = float ( ' inf ' ) NEW_LINE suml = 0 NEW_LINE sumr = 0 NEW_LINE index = - 1 NEW_LINE for c in range ( 0 , n + 1 , 1 ) : NEW_LINE INDENT suml = sum ( b1 [ : c + 1 ] ) NEW_LINE sumr = sum ( b2 ) NEW_LINE if suml >= sumr : NEW_LINE INDENT rem = suml - sumr NEW_LINE if rem < mini : NEW_LINE INDENT mini = rem NEW_LINE index = c NEW_LINE DEDENT DEDENT DEDENT return index , mini NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 14 , 4 , 41 , 1 ] NEW_LINE k = 7 NEW_LINE index , diff = makeDivisble ( arr , k ) NEW_LINE print ( index , diff ) NEW_LINE DEDENT