Make all array elements divisible by a number K | C ++ implementation to make the array elements divisible by 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; pair < int , int > makeDivisble ( int arr [ ] , int n , int k ) { vector < int > b1 ; vector < int > b2 ; int c , suml , sumr , index , rem ; for ( int i = 0 ; i < n ; i ++ ) b1 . push_back ( arr [ i ] % k ) ; for ( int j = 0 ; j < n ; j ++ ) if ( ( arr [ j ] % k ) != 0 ) b2 . push_back ( k - ( arr [ j ] % k ) ) ; else b2 . push_back ( 0 ) ; c = 0 ; float mini = INT_MAX ; suml = 0 ; sumr = 0 ; index = -1 ; for ( int c = 0 ; c < n ; c ++ ) { suml = accumulate ( b1 . begin ( ) , b1 . begin ( ) + c + 1 , 0 ) ; sumr = accumulate ( b2 . begin ( ) + c + 1 , b2 . end ( ) , 0 ) ; if ( suml >= sumr ) { rem = suml - sumr ; if ( rem < mini ) { mini = rem ; index = c ; } } } return make_pair ( index , mini ) ; } int main ( ) { int arr [ ] = { 1 , 14 , 4 , 41 , 1 } ; int k = 7 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; pair < int , int > ans ; ans = makeDivisble ( arr , n , k ) ; cout << ans . first << " ▁ " << ans . second ; return 0 ; }