Sum of first K numbers which are not divisible by N | Function to find the sum ; Find the last multiple of N ; Find the K - th non - multiple of N ; Calculate the sum of all elements from 1 to val ; Calculate the sum of all multiples of N between 1 to val ; Driver code
function findSum ( n , k ) { var val = parseInt ( k / ( n - 1 ) ) * n ; var rem = k % ( n - 1 ) ; if ( rem == 0 ) { val = val - 1 ; } else { val = val + rem ; } var sum = parseInt ( ( val * ( val + 1 ) ) / 2 ) ; var x = parseInt ( k / ( n - 1 ) ) ; var sum_of_multiples = parseInt ( ( x * ( x + 1 ) * n ) / 2 ) ; sum -= sum_of_multiples ; return sum ; } var n = 7 , k = 13 ; document . write ( findSum ( n , k ) )