Sum of all numbers in the given range which are divisible by M | C ++ program to find the sum of numbers divisible by M in the given range ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findSmallNum ( int N , int K ) { int rem = N % K ; if ( rem == 0 ) return N ; else return N - rem ; } int findLargeNum ( int N , int K ) { int rem = ( N + K ) % K ; if ( rem == 0 ) return N ; else return N + K - rem ; } int sumDivisibles ( int A , int B , int M ) { int sum = 0 ; int first = findSmallNum ( A , M ) ; int last = findLargeNum ( B , M ) ; if ( first < A ) first += M ; if ( last > B ) first -= M ; int n = ( B / M ) - ( A - 1 ) / M ; return n * ( first + last ) / 2 ; } int main ( ) { int A = 6 , B = 15 , M = 3 ; cout << sumDivisibles ( A , B , M ) ; return 0 ; }