Sum of the multiples of two numbers below N in C++

C++Server Side ProgrammingProgramming

In this problem, we have given three integers M1, M2, and N. Our task is to create a program to find the sum of multiples of two numbers below N.

Here, we will add all the elements below N which are multiples of either M1 or M2

Let’s take an example to understand the problem,

Input 

N = 13, M1 = 4, M2 = 6

Output  

20

Explanation − Number that are multiples of 4 and 6 that are less than 13 are 4, 6, 8, 12.

A simple solution to the problem is to be looping from 1 to N and adding all values that can be divided by M1 or M2.

Algorithm

Step 1 − sum = 0 , i = 0. Loop from i = 1 to N.

Step 1.1 − if (i%M1 == 0) or (i%M2 == 0), sum + = i

Step 2 − Return sum.

Example

Program to illustrate the working of our solution,

 Live Demo

#include <iostream<
using namespace std;
int calcMulSum(int N, int M1, int M2){
   int sum = 0;
   for (int i = 0; i < N; i++)
      if (i%M1 == 0 || i%M2 == 0)
   sum += i;
   return sum;
}
int main(){
   int N = 24, M1 = 4, M2 = 7;
   cout<<"The sum of multiples of "<<M1<<" and "<<M2<<" below "<<N<<" is "<<calcMulSum(N, M1, M2);
   return 0;
}

Output

The sum of multiples of 4 and 7 below 24 is 102

This is not the best solution to our problem as it takes O(n) time complexity.

A better solution will be using mathematical formulas for the sum of series.

Here, we will use the formula for the sum of the series. The final sum will be the (multiples of M1 + multiples of M2 - multiples of M1*M2)

Sum of multiple of x upto n terms is given by,

Sum(X) = (n * (1+n) * X)/2

Let’s formulate the sum,

sum = ( ( ((n/M1)*(1+(n/M1))*M1)/2) + ((n/M2)*(1+(n/M2))*M2)/2 ) - ((n/M1*M2)*(1+(n/M1*M2))*M1*M2)/2 ) )

Example

Program to illustrate the solution,

 Live Demo

#include <iostream>
using namespace std;
int calcMulSum(int N, int M1, int M2){
   N--;
   return (((N/M1) * (1 + (N/M1)) * M1 / 2) + ((N/M2) * (1 + (N/M2)) * M2 / 2) - ((N/(M1*M2)) * (1 + (N/(M1*M2))) * (M1*M2) / 2));
}
int main(){
   int N = 24, M1 = 4, M2 = 7;
   cout<<"The sum of multiples of "<<M1<<" and "<<M2<<" below "<<N<<" is "<<calcMulSum(N, M1, M2);
   return 0;
}

Output

The sum of multiples of 4 and 7 below 24 is 102
raja
Published on 06-Aug-2020 08:24:39
Advertisements