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

Finding the sum of numbers up to N that are divisible by 2 or 5 can be efficiently calculated using the inclusion-exclusion principle. Instead of iterating through all numbers, we use mathematical formulas to compute the sum in O(1) time complexity.

Syntax

sum = sum_divisible_by_2 + sum_divisible_by_5 - sum_divisible_by_10

Mathematical Approach

The solution uses three formulas based on arithmetic progression −

  • Sum of numbers divisible by 2: Sum2 = ((n / 2) * (4 + (n / 2 - 1) * 2)) / 2
  • Sum of numbers divisible by 5: Sum5 = ((n / 5) * (10 + (n / 5 - 1) * 5)) / 2
  • Sum of numbers divisible by 10: Sum10 = ((n / 10) * (20 + (n / 10 - 1) * 10)) / 2

We subtract Sum10 because numbers divisible by both 2 and 5 (i.e., divisible by 10) are counted twice in Sum2 and Sum5.

Example

Here's a complete program to calculate the sum of numbers up to N divisible by 2 or 5 −

#include <stdio.h>

int main() {
    int n = 25;
    long int sum2, sum5, sum10;
    
    /* Calculate sum of numbers divisible by 2 */
    sum2 = ((n / 2) * (4 + (n / 2 - 1) * 2)) / 2;
    
    /* Calculate sum of numbers divisible by 5 */
    sum5 = ((n / 5) * (10 + (n / 5 - 1) * 5)) / 2;
    
    /* Calculate sum of numbers divisible by 10 */
    sum10 = ((n / 10) * (20 + (n / 10 - 1) * 10)) / 2;
    
    /* Apply inclusion-exclusion principle */
    long int sum = sum2 + sum5 - sum10;
    
    printf("Numbers up to %d:<br>", n);
    printf("Sum divisible by 2: %ld<br>", sum2);
    printf("Sum divisible by 5: %ld<br>", sum5);
    printf("Sum divisible by 10: %ld<br>", sum10);
    printf("Sum divisible by 2 or 5: %ld<br>", sum);
    
    return 0;
}
Numbers up to 25:
Sum divisible by 2: 156
Sum divisible by 5: 75
Sum divisible by 10: 30
Sum divisible by 2 or 5: 201

How It Works

For N = 25:

  • Divisible by 2: 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24 ? Sum = 156
  • Divisible by 5: 5, 10, 15, 20, 25 ? Sum = 75
  • Divisible by 10: 10, 20 ? Sum = 30 (counted in both above)
  • Final result: 156 + 75 - 30 = 201

Key Points

  • This method has O(1) time complexity compared to O(n) for the naive approach
  • Uses inclusion-exclusion principle to avoid double-counting
  • Efficient for very large values of N

Conclusion

The mathematical approach using inclusion-exclusion principle provides an efficient solution with constant time complexity. This method is ideal when dealing with large values of N where iterative approaches become impractical.

Updated on: 2026-03-15T11:27:26+05:30

562 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements