/*
Deoarece se apropie Craciunul cu pasi repezi, Petrica vrea sa fie mai bun.
Lui ii plac problemele cu limita de timp mare asa ca el vrea sa gaseasca cel
mai mic numar format doar cu cifrele 2, 3, 5 si 7 care da restul N la impartirea
cu P.
Input:
Fişierul de intrare cifre4.in contine pe prima linie un numar natural T
ce semnifica numarul de teste. Pe urmatoarele T linii se afla cate doua
numere naturale N si P, cu semnificatia din enunt.
Output:
În fişierul de ieşire cifre4.out se vor afla T linii, pe linia i se va
afla raspunsul pentru al i-lea test, sau -1 in cazul in care nu exista solutie.
Restrictii:
T = 5
1 ≤ P ≤ 5 * 106
1 ≤ N ≤ P - 1
Example:
Input:
3
52 100
11 100
51 1123
Output:
52
-1
322352
*/
#include <iostream>
#define FIN "cifre4.in"
#define FOUT "cifre4.out"
using namespace std;
int arr[4] = {2, 3, 5, 7}, sol[100];
int numTests;
long long p[6], q[6], good[10];
void check(int len) {
long long x = 0;
for(int i = 0; i < len; i++) {
x = x * 10 + sol[ i ];
}
for(int i = 0; i < numTests; ++i) {
if( good[ i ] == -1 )
if( x % q[ i ] == p[ i ] ) good[i] = x;
}
}
void back(int pos, int len) {
if(pos == len) {
check(len);
return;
} else {
for(int j = 0; j < 4; ++j) {
sol[pos] = arr[j];
back(pos+1, len);
}
}
}
int main(int argc, char const *argv[]) {
//freopen(FIN, "r", stdin);
//freopen(FOUT, "w", stdout);
scanf("%d", &numTests);
for(int i = 0; i < numTests; ++i) scanf("%lld %lld", &p[i], &q[i]), good[i] = -1;
for(int i = 1; i <= 12; ++i) {
back(0, i);
}
for(int i = 0; i < numTests; ++i) cout<<good[i]<<"\n";
return 0;
}
LyoKRGVvYXJlY2Ugc2UgYXByb3BpZSBDcmFjaXVudWwgY3UgcGFzaSByZXBlemksIFBldHJpY2EgdnJlYSBzYSBmaWUgbWFpIGJ1bi4KTHVpIGlpIHBsYWMgcHJvYmxlbWVsZSBjdSBsaW1pdGEgZGUgdGltcCBtYXJlIGFzYSBjYSBlbCB2cmVhIHN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xWzZdLCBnb29kWzEwXTsKCnZvaWQgY2hlY2soaW50IGxlbikgewoKICBsb25nIGxvbmcgeCA9IDA7CgogICAgIGZvcihpbnQgaSA9IDA7IGkgPCBsZW47IGkrKykgewoKICAgICAgICAgeCA9IHggKiAxMCArIHNvbFsgaSBdOwogICAgIH0KCiAgICAgZm9yKGludCBpID0gMDsgaSA8IG51bVRlc3RzOyArK2kpIHsKCiAgICAgICAgIGlmKCBnb29kWyBpIF0gPT0gLTEgKQoKICAgICAgICAgICAgaWYoIHggJSBxWyBpIF0gPT0gcFsgaSBdICkgZ29vZFtpXSA9IHg7CiAgICAgfQp9Cgp2b2lkIGJhY2soaW50IHBvcywgaW50IGxlbikgewoKICAgIGlmKHBvcyA9PSBsZW4pIHsKCiAgICAgICBjaGVjayhsZW4pOwoKICAgICAgIHJldHVybjsKCiAgICB9IGVsc2UgewoKICAgICAgZm9yKGludCBqID0gMDsgaiA8IDQ7ICsraikgewoKICAgICAgICAgc29sW3Bvc10gPSBhcnJbal07CgogICAgICAgICBiYWNrKHBvcysxLCBsZW4pOwogICAgICB9CiAgICB9Cn0KCmludCBtYWluKGludCBhcmdjLCBjaGFyIGNvbnN0ICphcmd2W10pIHsKCiAgLy9mcmVvcGVuKEZJTiwgInIiLCBzdGRpbik7CgogIC8vZnJlb3BlbihGT1VULCAidyIsIHN0ZG91dCk7CgogIHNjYW5mKCIlZCIsICZudW1UZXN0cyk7CgogIGZvcihpbnQgaSA9IDA7IGkgPCBudW1UZXN0czsgKytpKSBzY2FuZigiJWxsZCAlbGxkIiwgJnBbaV0sICZxW2ldKSwgZ29vZFtpXSA9IC0xOwoKICBmb3IoaW50IGkgPSAxOyBpIDw9IDEyOyArK2kpIHsKCiAgICAgIGJhY2soMCwgaSk7CiAgfQoKICBmb3IoaW50IGkgPSAwOyBpIDwgbnVtVGVzdHM7ICsraSkgY291dDw8Z29vZFtpXTw8IlxuIjsKCiAgcmV0dXJuIDA7Cn0K