Sum of multiples of Array elements within a given range [ L , R ] | C ++ program for the above approach ; Function to find the sum of all multiples of N up to K ; Calculate the sum ; Return the sum ; Function to find the total sum ; If L is divisible by a [ i ] ; Otherwise ; Return the final sum ; Driver Code ; Given array arr [ ] ; Given range ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calcSum ( int k , int n ) { int value = ( k * n * ( n + 1 ) ) / 2 ; return value ; } int findSum ( int * a , int n , int L , int R ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( L % a [ i ] == 0 && L != 0 ) { sum += calcSum ( a [ i ] , R / a [ i ] ) - calcSum ( a [ i ] , ( L - 1 ) / a [ i ] ) ; } else { sum += calcSum ( a [ i ] , R / a [ i ] ) - calcSum ( a [ i ] , L / a [ i ] ) ; } } return sum ; } int main ( ) { int arr [ ] = { 2 , 7 , 3 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int L = 7 ; int R = 20 ; cout << findSum ( arr , N , L , R ) ; return 0 ; }