Sum of first N natural numbers which are divisible by 2 and 7 in C++


In this problem, we are given a number N. Our task is to find the sum of first N natural numbers which are divisible by 2 and 7.

So, here we will be given a number N, the program will find the sum of numbers between 1 to N that is divisible by 2 and 7.

Let’s take an example to understand the problem,

Input

N = 10

Output

37

Explanation

sum = 2 + 4 + 6 + 7 + 8 + 10 = 37

So, the basic idea to solve the problem is to find all the numbers that are divisible by 2 or by 7. This sum will be −

Sum of numbers divisible by 2 + sum of numbers divisible by 7 - sum of number divisible by 14.

All these sums can be generated using A.P. formulas,

S2 = [( (N/2)/2) * ( (2*2)+((N/2-1)*2) )]
S7 = [( (N/7)/2) * ( (2*7)+((N/7-1)*7) )]
S14 = [( (N/14)/2) * ( (2*14)+((N/2-1)*14) )]

The final sum,

Sum = S2 + S7 - S14
Sum = [( (N/2)/2) * ( (2*2)+((N/2-1)*2) )] + [( (N/7)/2) * ( (2*7)+((N/7-1)*7) )] - [( (N/14)/2) * ( (2*14)+((N/2-1)*14) )]

Example

Program to illustrate the solution,

 Live Demo

#include <iostream>
using namespace std;
int findSum(int N) {
   return ( ((N/2)*(2*2+(N/2-1)*2)/2) + ((N/7)*(2*7+(N/7-1)*7)/2) - ((N/14)*(2*14+(N/14-1)*14)/2) );
}
int main(){
   int N = 42;
   cout<<"The sum of natural numbers which are divisible by 2 and 7 is "<<findSum(N);
   return 0;
}

Output

The sum of natural numbers which are divisible by 2 and 7 is 525

Updated on: 05-Aug-2020

100 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements