Find the sum of all numbers between 1 and N divisible by either x or y
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
In mathematical problems and algorithmic challenges, it often becomes crucial to efficiently calculate sums involving specific properties, such as being divisible by given factors. One typical problem is to determine the sum of all numbers between 1 and N that are divisible by either x or y. This problem has both practical applications in areas like computer science for generating sequences and also provides a solid ground for understanding concepts such as inclusion-exclusion principle.
Approach
To solve the problem of finding the sum of all numbers divisible by either x or y, we can make use of the inclusion-exclusion principle, ensuring we do not double-count numbers divisible by both.
Steps:
- Find all numbers divisible by x: Compute the count as
floor(N / x), which gives how many multiples ofxappear in the range. - Find all numbers divisible by y: Compute
floor(N / y)to count the multiples ofy. - Sum multiples of x: Use the arithmetic series formula
S_x = x * (k_x * (k_x + 1) / 2)wherek_x = floor(N / x). - Sum multiples of y: Apply the same logic with
S_y = y * (k_y * (k_y + 1) / 2)andk_y = floor(N / y). - Sum common multiples: Determine
lcm(x, y)and computeS_{xy} = lcm(x, y) * (k_{xy} * (k_{xy} + 1) / 2)withk_{xy} = floor(N / lcm(x, y)). - Apply inclusion-exclusion: Combine the partial sums with
S_total = S_x + S_y - S_{xy}to avoid double counting.
Example
Consider N = 20, x = 3, and y = 5.
- Numbers divisible by x:
k_x = floor(20 / 3) = 6, soS_x = 3 * (6 * (6 + 1) / 2) = 63. - Numbers divisible by y:
k_y = floor(20 / 5) = 4, soS_y = 5 * (4 * (4 + 1) / 2) = 50. - Common multiples of x and y:
lcm(3, 5) = 15, givingk_{xy} = floor(20 / 15) = 1, soS_{xy} = 15 * (1 * (1 + 1) / 2) = 15. - Total using inclusion-exclusion:
S_total = 63 + 50 - 15 = 98.
The sum of all numbers between 1 and 20 that are divisible by either 3 or 5 is therefore 98.
Key Points Summary
| Step | Expression | Calculation Result |
| Numbers divisible by x | k_x = floor(N / x) | 6 |
| Sum multiples of x | S_x = x * (k_x * (k_x + 1) / 2) | 63 |
| Numbers divisible by y | k_y = floor(N / y) | 4 |
| Sum multiples of y | S_y = y * (k_y * (k_y + 1) / 2) | 50 |
| Common multiples | k_{xy} = floor(N / lcm(x, y)) | 1 |
| Sum common multiples | S_{xy} = lcm(x, y) * (k_{xy} * (k_{xy} + 1) / 2) | 15 |
| Total sum using inclusion-exclusion | S_total = S_x + S_y - S_{xy} | 98 |
Conclusion
Calculating the sum of numbers between 1 and N divisible by either x or y involves effectively using arithmetic series formulas paired with the inclusion-exclusion principle to ensure that multiples are not double-counted. This method is both computationally efficient and conceptually clear for large ranges and diverse conditions.

