Sum of the numbers up to N that are divisible by 2 or 5 in c programming


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

Example

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

Output

Sum is 201
raja
Published on 09-Aug-2019 15:07:58
Advertisements