- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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,

#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

- Related Questions & Answers
- Sum of first N natural numbers which are divisible by X or Y
- Sum of sum of first n natural numbers in C++
- Check if product of first N natural numbers is divisible by their sum in Python
- Sum of first n natural numbers in C Program
- Number of pairs from the first N natural numbers whose sum is divisible by K in C++
- Sum of squares of first n natural numbers in C Program?
- C Program for cube sum of first n natural numbers?
- C++ Program for cube sum of first n natural numbers?
- Find k numbers which are powers of 2 and have sum N in C++
- Sum of square-sums of first n natural numbers
- C++ Program for Sum of squares of first n natural numbers?
- Sum of the numbers up to N that are divisible by 2 or 5 in c programming
- Program to find sum of first n natural numbers in C++
- Program for cube sum of first n natural numbers in C++
- Sum of all subsets of a set formed by first n natural numbers

Advertisements