Sum of array elements possible by appending arr [ i ] / K to the end of the array K times for array elements divisible by K | C ++ program for the above approach ; Function to calculate sum of array elements after adding arr [ i ] / K to the end of the array if arr [ i ] is divisible by K ; Stores the sum of the array ; Traverse the array arr [ ] ; Traverse the vector ; If v [ i ] is divisible by K ; Iterate over the range [ 0 , K ] ; Update v ; Otherwise ; Traverse the vector v ; Return the sum of the updated array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sum ( int arr [ ] , int N , int K ) { int sum = 0 ; vector < long long > v ; for ( int i = 0 ; i < N ; i ++ ) { v . push_back ( arr [ i ] ) ; } for ( int i = 0 ; i < v . size ( ) ; i ++ ) { if ( v [ i ] % K == 0 ) { long long x = v [ i ] / K ; for ( int j = 0 ; j < K ; j ++ ) { v . push_back ( x ) ; } } else break ; } for ( int i = 0 ; i < v . size ( ) ; i ++ ) sum = sum + v [ i ] ; return sum ; } int main ( ) { int arr [ ] = { 4 , 6 , 8 , 2 } ; int K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << sum ( arr , N , K ) ; return 0 ; }