Sum of array elements possible by appending arr [ i ] / K to the end of the array K times for array elements divisible by K | Java 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 ; Stores the array elements ; Traverse the array ; Stores if the operation should be formed or not ; Traverse the vector V ; If flag is false and if v [ i ] is divisible by K ; Otherwise , set flag as true ; Increment the sum by v [ i % N ] ; Return the resultant sum ; Driver Code
import java . io . * ; import java . util . * ; class GFG { static int sum ( int arr [ ] , int N , int K ) { int sum = 0 ; ArrayList < Integer > v = new ArrayList < Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { v . add ( arr [ i ] ) ; } boolean flag = false ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { if ( ! flag && v . get ( i ) % K == 0 ) v . add ( v . get ( i ) / K ) ; else { flag = true ; } sum = sum + v . get ( i % N ) ; } return sum ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 6 , 8 , 2 } ; int K = 2 ; int N = arr . length ; System . out . println ( sum ( arr , N , K ) ) ; } }