- 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
- Find k numbers which are powers of 2 and have sum N in C++
- Sum of squares of first n natural numbers in C Program?
- Sum of square-sums of first n natural numbers
- C Program for cube sum of first n natural numbers?
- C++ Program for cube sum of first n natural numbers?
- Sum of the numbers up to N that are divisible by 2 or 5 in c programming
- C++ Program for Sum of squares of first n natural numbers?
- 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
- C Program for the cube sum of first n natural numbers?

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

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) )]

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; }

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

Advertisements