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
def findSum ( n , k ) : NEW_LINE INDENT val = ( k // ( n - 1 ) ) * n ; NEW_LINE rem = k % ( n - 1 ) ; NEW_LINE if ( rem == 0 ) : NEW_LINE INDENT val = val - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT val = val + rem ; NEW_LINE DEDENT sum = ( val * ( val + 1 ) ) // 2 ; NEW_LINE x = k // ( n - 1 ) ; NEW_LINE sum_of_multiples = ( x * ( x + 1 ) * n ) // 2 ; NEW_LINE sum -= sum_of_multiples ; NEW_LINE return sum ; NEW_LINE DEDENT n = 7 ; k = 13 ; NEW_LINE print ( findSum ( n , k ) ) NEW_LINE