- Related Questions & Answers
- Average numbers in array in C Programming
- Add minimum number to an array so that the sum becomes even in C programming
- Arithmetic Mean in C programming
- C Program to Multiply two Floating Point Numbers?
- Concatenate a string given number of times in C++ programming
- Write a program to Delete a Tree in C programming
- Write a function that returns 2 for input 1 and returns 1 for 2 in C programming
- Ways to paint N paintings such that adjacent paintings don’t have same colors in C programming
- Surface Area and Volume of Hexagonal Prism in C programming
- Superperfect Number in C programming
- Super Prime in c programming
- Sums of ASCII values of each word in a sentence in c programming
- Sum triangle from an array in C programming
- C Programming for sum of the series 0.6, 0.06, 0.006, 0.0006, …to n terms
- C Programming for Sum of sequence 2, 22, 222, ………

- 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 n natural numbers that are divisible by 2 or 5 can be found by finding the sum of all natural numbers up to N that is divisible by 2 and sum of all natural numbers up to N that is divisible by 5. Adding these two sums and then subtracting it by the sum of natural numbers up to N that is divisible by 10, this gives us the desired result. This method is an efficient method that can be used to find sum up to large values of n.

Some of you must be thinking of using a loop and conditional statement and then adding all those numbers that are divisible by 2 or 5 but this method is inefficient because it has a time complexity of the order n. This means that for large values of n the program will run the loop n number of times. And this execution will make the program heavier.

Formula to find the sum of n natural numbers divisible by 2

Sum2 = ((n / 2) * (4 + (n / 2 - 1) * 2)) / 2

Formula to find the sum of n natural numbers divisible by 5

Sum5 = ((n / 5) * (10 + (n / 5 - 1) * 5)) / 2

Formula to find the sum of n natural numbers divisible by 10

Sum10 = ((n / 10) * (20 + (n / 10 - 1) * 10)) / 2

Desired output

Sum = Sum2 + Sum5 - Sum10

#include <stdio.h> int main() { int n = 25; long int sum2, sum5, sum10; sum2 = ((n / 2) * (4 + (n / 2 - 1) * 2)) / 2; sum5 = ((n / 5) * (10 + (n / 5 - 1) * 5)) / 2; sum10 = ((n / 10) * (20 + (n / 10 - 1) * 10)) / 2; long int sum = sum2 + sum5 - sum10; printf("Sum is %d", sum); return 0; }

Sum is 201

Advertisements