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 ; Driver code ; A and B define the range , M is the dividend ; Printing the result
def findSmallNum ( N , K ) : NEW_LINE INDENT rem = N % K NEW_LINE if ( rem == 0 ) : NEW_LINE INDENT return N NEW_LINE DEDENT else : NEW_LINE INDENT return N - rem NEW_LINE DEDENT DEDENT def findLargeNum ( N , K ) : NEW_LINE INDENT rem = ( N + K ) % K NEW_LINE if ( rem == 0 ) : NEW_LINE INDENT return N NEW_LINE DEDENT else : NEW_LINE INDENT return N + K - rem NEW_LINE DEDENT DEDENT def sumDivisibles ( A , B , M ) : NEW_LINE INDENT sum = 0 NEW_LINE first = findSmallNum ( A , M ) NEW_LINE last = findLargeNum ( B , M ) NEW_LINE if ( first < A ) : NEW_LINE INDENT first += M NEW_LINE DEDENT if ( last > B ) : NEW_LINE INDENT first -= M NEW_LINE DEDENT n = ( B // M ) - ( A - 1 ) // M NEW_LINE return n * ( first + last ) // 2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 6 NEW_LINE B = 15 NEW_LINE M = 3 NEW_LINE print ( sumDivisibles ( A , B , M ) ) NEW_LINE DEDENT