Sum of all numbers in the given range which are divisible by M | Function to find the largest number smaller than or equal to N that is divisible by K ; Finding the remainder when N is divided by K ; If the remainder is 0 , then the number itself is divisible by K ; Else , then the difference between N and remainder is the largest number which is divisible by K ; Function to find the smallest number greater than or equal to N that is divisible by K ; Finding the remainder when N is divided by K ; If the remainder is 0 , then the number itself is divisible by K ; Else , then the difference between N and remainder is the largest number which is divisible by K ; Function to find the sum of numbers divisible by M in the given range ; Variable to store the sum ; To bring the smallest and largest numbers in the range [ A , B ] ; To count the number of terms in the AP ; Sum of n terms of an AP ; A and B define the range , M is the dividend ; Printing the result
function findSmallNum ( N , K ) { var rem = N % K ; if ( rem == 0 ) return N ; else return N - rem ; } function findLargeNum ( N , K ) { var rem = ( N + K ) % K ; if ( rem == 0 ) return N ; else return N + K - rem ; } function sumDivisibles ( A , B , M ) { var sum = 0 ; var first = findSmallNum ( A , M ) ; var last = findLargeNum ( B , M ) ; if ( first < A ) first += M ; if ( last > B ) first -= M ; var n = ( parseInt ( B / M ) - parseInt ( ( A - 1 ) / M ) ) ; return n * ( first + last ) / 2 ; } var A = 6 , B = 15 , M = 3 ; document . write ( sumDivisibles ( A , B , M ) ) ;