Author : Udynamo
Required Knowledge : String Modulo, Modulo Arithmetic
Time Complexity :
Editorialist : Udynamo
First, let's understand our goal, which is to make divisible by . To achieve this, we can perform one operation any number of times: add to . This gives us a clear mathematical goal: find the smallest non-negative integer that satisfies the equation:
The first thing to notice is that is a huge number given as a string, so we can't store it in a standard long long. Let's simplify our equation using a key property of modular arithmetic:
Applying this to our goal equation, we get:
This shows that we don't need the entire number . We only need its remainder when divided by , which we'll call .
So, our new, simpler goal is to find the smallest such that:
Since we can't calculate directly, we will calculate it using string modulo by processing the string digit by digit. We initialize , and for each digit c in the string, we update . After looping through all the digits, the final value of is exactly .
With the remainder calculated, we just need to test values of starting from to .
Why check only from to
We only need to check from to because the sequence of remainders, , is periodic and must repeat every steps.
Consider the remainder at step and step :
Remainder at :
Remainder at :
Let's expand the second one:
Since is always , this simplifies to:
This proves the remainder at step is identical to the one at step . The pattern of remainders from to will simply repeat.
We loop with from to . The first value of that satisfies our equation, , is the smallest one, and that is our answer.
If we finish the entire loop (from to ) and no satisfies the equation, it means a solution is impossible (because the pattern just repeats). In this case, we output .
// Author : Udynamo
#include <bits/stdc++.h>
#define int long long
using namespace std;
const bool test_cases = true;
const int mod = 1e9 + 7, INF = 1e18;
void UNsolve() {
string N;
cin >> N;
int M, D;
cin >> M >> D;
//String Modulo
int rem = 0;
for(int i = 0; i < N.size(); i++){
rem = rem * 10 + (N[i] - '0');
rem %= D;
}
for(int i = 0; i < D; i++){
if((rem + (M * i) % D) % D == 0){
cout << i << endl;
return;
}
}
//impossible case
cout << -1 << endl;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
if (test_cases) cin >> t;
while (t--) {
UNsolve();
}
return 0;
}
def solve():
n, m, d = input().split()
m = int(m)
d = int(d)
r = 0
for c in n:
r = (r * 10 + (ord(c) - ord('0'))) % d
for i in range(d + 1):
if (r + m * i) % d == 0:
print(i)
return
print(-1)
t = int(input())
for _ in range(t):
solve()