Sum of first N natural numbers which are divisible by X or Y

CServer Side ProgrammingProgramming

Adding up all natural numbers up to n, that are divisible by X or Y is selecting all the numbers that are divisible by X or Y and adding them to a variable that stores the sum.

To find the sum of the first N natural numbers which are divisible by X or Y, there are two methods −

  • Using loops and conditional statements
  • Using formula

Method 1 − Using loops and conditional statements

This method uses a loop that counts up to n numbers and selects numbers that are divisible by X or Y and adds them and save to a variables at each iteration.

Example Code

 Live Demo

#include <stdio.h>
int main(void) {
   int n = 54;
   int x = 2 ;
   int y = 5;
   int sum = 0;
   for(int i = 0; i<= n; i++) {
      if(i%x == 0 || i% y == 0)
         sum = sum + i;
   }
   printf("sum of %d natural numbers divisible by %d and %d is %d" ,n,x,y,sum);
   return 0;
}

Output

sum of 54 natural numbers divisible by 2 and 5 is 881

Method 2 − Using formula ,

This method uses the formula to find the sum of the first n number divisible by a number.

This can be found using the formula − SN/X = ((N/X)/2) * (2 * X + (N/X - 1) * X)

Using this formula the sum of n natural numbers divisible by x is found − S n/x = ((n/x)/2) * (2 * x + (n/x - 1) * x)

Using this formula the sum of n natural numbers divisible by y is found − S n/y = ((n/y)/2) * (2 * y + (n/y - 1) * y)

Now, Using this formula the sum of n natural numbers divisible by x and y is found : S n/x*y = ((n/(x*y)/2) * (2 * (x*y) + (n/(x*y) - 1) * (x*y))

Now, we will add the sum of x and sum of y and subtract sum of x*y that are add two times.

Example Code

 Live Demo

#include <stdio.h>
int main() {
   int n = 54;
   int x = 2, y = 5;
   int Sx, Sy, Sxy, sum;
   Sx = ((n / x)) * (2 * x + (n / x - 1) * x) / 2;
   Sy = ((n / y)) * (2 * y + (n / y - 1) * y) / 2;
   Sxy= ((n / (x * y))) * (2 * (x * y) + (n / (x * y) - 1) * (x * y))/ 2;
   sum = Sx + Sy - Sxy;
   printf("sum of %d natural numbers divisible by %d and %d is %d" ,n,x,y,sum);
   return 0;
}

Output

sum of 54 natural numbers divisible by 2 and 5 is 881

The second method is better because it does not use any loop that means better time complexity. But if the input cases are smaller than first one can also be used. But for large input cases the second method is not the best option.

raja
Published on 15-Jul-2019 12:14:00
Advertisements