Sub topic 17
Counting Integer Solutions Without Off-by-One Errors
This chapter assumes you can already solve linear, rational and multiple-modulus inequalities and write the answer as an interval. Here the job is the last step that CAT questions often ask for: turning an interval into an exact count of integers.
The two counting formulas
Most mistakes come from treating closed and open endpoints the same way. Use these formulas, which also work when the endpoints are not integers.
| Interval | Number of integers | Example | Count |
|---|---|---|---|
| [a, b] | floor(b) − ceil(a) + 1 | [−2.5, 4] | 4 − (−2) + 1 = 7 |
| (a, b) | ceil(b) − floor(a) − 1 | (−4, 5) | 5 − (−4) − 1 = 8 |
| [a, b) | ceil(b) − ceil(a) | [1, 6) | 6 − 1 = 5 |
| (a, b] | floor(b) − floor(a) | (1, 6] | 6 − 1 = 5 |
When a and b are integers, [a, b] holds b − a + 1 integers and (a, b) holds b − a − 1. A half-open interval has exactly b − a.
Worked example 1: two modulus terms
Count the integers x with |x − 3| + |x + 2| < 9.
The critical points are x = −2 and x = 3.
- For x ≥ 3: 2x − 1 < 9, so x < 5.
- For −2 ≤ x < 3: the sum is 5, and 5 < 9 always holds.
- For x < −2: −2x + 1 < 9, so x > −4.
The solution is (−4, 5). Both ends are open, so the count is 5 − (−4) − 1 = 8, which covers the integers −3 through 4.
Worked example 2: a rational inequality on a range
Count the integers x with −10 ≤ x ≤ 10 that satisfy (x − 1)(x + 2)/(x − 3) ≥ 0.
The wavy curve method gives [−2, 1] ∪ (3, ∞). The interval [−2, 1] contains 4 integers. Within the allowed range, (3, 10] contains 10 − 3 = 7. The total is 11. Note that x = 3 is excluded because the denominator is zero there.
count1 = sum(1 for x in range(-100, 101) if abs(x - 3) + abs(x + 2) < 9)
def ok(x):
return x != 3 and (x - 1) * (x + 2) / (x - 3) >= 0
count2 = sum(1 for x in range(-10, 11) if ok(x))
print(count1, count2) # 8 11Counting lattice points in two dimensions
For |x| + |y| ≤ n, take each row y = k. It has |x| ≤ n − |k|, which gives 2(n − |k|) + 1 integer values of x. Adding these over all rows gives 2n² + 2n + 1. For n = 3 that is 25. The strict version |x| + |y| < n has the same points as |x| + |y| ≤ n − 1, so it has 2(n − 1)² + 2(n − 1) + 1 points.
Exercise
How many integers x satisfy |2x − 5| ≤ 7?
Show answer
−7 ≤ 2x − 5 ≤ 7 gives −1 ≤ x ≤ 6. This is a closed interval, so the count is 6 − (−1) + 1 = 8.
Exercise
How many integer points (x, y) satisfy |x| + |y| < 4?
Show answer
This is the same as |x| + |y| ≤ 3, so the count is 2(9) + 2(3) + 1 = 25.
Exercise
How many integers satisfy (x + 3)(x − 4)/(x − 1) < 0?
Show answer
The sign chart gives (−∞, −3) ∪ (1, 4). The first interval contains infinitely many integers, so the count is infinite. Restricted to x > −3, only (1, 4) is left, which contains 4 − 1 − 1 = 2 integers: 2 and 3.