#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int MOD = 1e9 + 7;
void solve(){
ll n, k;
cin >> n >> k;
if(k == 1){
cout << (n % MOD)<< "\n";
return;
}
ll p = k - 1, q = k - 1;
ll cnt = 2;
while(q != 0){
ll next = (p + q);
next %= k;
p = q;
q = next;
cnt++;
cnt %= MOD;
}
n %= MOD;
cnt %= MOD;
n *= cnt;
n %= MOD;
cout << n << "\n";
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
cin >> t;
for(int i = 1; i <= t; i++){
solve();
}
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CiNkZWZpbmUgbGwgbG9uZyBsb25nCgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKY29uc3QgaW50IE1PRCA9IDFlOSArIDc7Cgp2b2lkIHNvbHZlKCl7CglsbCBuLCBrOwoJY2luID4+IG4gPj4gazsKCQoJaWYoayA9PSAxKXsKCQljb3V0IDw8IChuICUgTU9EKTw8ICJcbiI7CgkJcmV0dXJuOwoJfQoJbGwgcCA9IGsgLSAxLCBxID0gayAtIDE7CgkKCWxsIGNudCA9IDI7Cgl3aGlsZShxICE9IDApewoJCWxsIG5leHQgPSAocCArIHEpOwoJCW5leHQgJT0gazsKCQlwID0gcTsKCQlxID0gbmV4dDsKCQljbnQrKzsKCQljbnQgJT0gTU9EOwoJfQoJbiAlPSBNT0Q7CgljbnQgJT0gTU9EOwoJbiAqPSBjbnQ7CgluICU9IE1PRDsKCWNvdXQgPDwgbiA8PCAiXG4iOwoJCn0KCmludCBtYWluKCl7Cglpb3NfYmFzZTo6c3luY193aXRoX3N0ZGlvKGZhbHNlKTsKCWNpbi50aWUobnVsbHB0cik7CgkKCWludCB0ID0gMTsKCWNpbiA+PiB0OwoJCglmb3IoaW50IGkgPSAxOyBpIDw9IHQ7IGkrKyl7CgkJc29sdmUoKTsKCX0KCXJldHVybiAwOwp9