To solve the problem of finding the summation of all numbers from 1 to ( r ) that are divisible by either ( a ) or ( b ), and then taking the result modulo ( d ), we can use the principle of Inclusion-Exclusion and some arithmetic formulae to handle large numbers efficiently.
Here’s a step-by-step process:
Steps to Approach the Problem:
-
Inclusion-Exclusion Principle:
- Find the sum of multiples of ( a ).
- Find the sum of multiples of ( b ).
- Subtract the sum of multiples of ( \text{lcm}(a, b) ) to avoid double-counting numbers that are multiples of both ( a ) and ( b ).
-
Sum of Multiples:
- To find the sum of multiples of an integer ( n ) up to ( r ), find the largest multiple of ( n ) that is ( \leq r ). This is given by ( m = \lfloor \frac{r}{n} \rfloor ).
- The multiples of ( n ) are ( n, 2n, 3n, \ldots, mn ).
- The sum of the first ( m ) multiples of ( n ) is given by:
[
\text{Sum} = n \times \frac{m \times (m + 1)}{2}
]
- This formula is derived from the sum of the first ( m ) natural numbers.
-
Computing (\text{lcm}(a, b)):
- Use the formula (\text{lcm}(a, b) = \frac{|a \times b|}{\text{gcd}(a, b)}).
-
Modulo Operation:
- Throughout the calculations, take care to apply modulo ( d ) to keep numbers manageable and to prevent overflow.
-
Iterating through Test Cases:
- Perform the above calculations independently for each test case.
Here is an example of how to implement this algorithm in Python:
import sys
import math
input = sys.stdin.readline
def sum_of_multiples(n, M):
m = M // n
return n * m * (m + 1) // 2
def solve_test_cases():
T = int(input())
for _ in range(T):
r, a, b, d = map(int, input().split())
sum_a = sum_of_multiples(a, r) % d
sum_b = sum_of_multiples(b, r) % d
lcm_ab = (a * b) // math.gcd(a, b)
sum_lcm_ab = sum_of_multiples(lcm_ab, r) % d
result = (sum_a + sum_b - sum_lcm_ab) % d
print(result)
solve_test_cases()
Explanation:
- sum_of_multiples(n, M): Calculates the sum of multiples of ( n ) up to ( M ).
- We read the number of test cases ( T ), then loop over each test case, computing the necessary sums using the inclusion-exclusion principle.
- Finally, we ensure the result is modulo ( d ) and print it.
This approach is efficient given the constraints ( 1 \leq r, a, b, d \leq 10^{18} ) and ( T \leq 100,000 ), as it reduces the problem to basic arithmetic calculations and efficient modular operations.