#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for (int i=0; i < n; i++)
using ll = long long;

void chmax(ll& x, ll y) { x = max(x,y); }
const ll INF = 1e18;
ll dp[105][105];

tuple<ll,ll,ll> extgcd(ll a, ll b){
  if (b == 0) return {a,1,0};
  ll g,x,y;
  tie(g,x,y) = extgcd(b, a%b);
  return {g,y,x-a/b*y};
}

int main() {
  int T;
  cin >> T;
  rep(t,T){
    int N,S,K;
    cin >> N >> S >> K;
    ll g,x,y;
    tie(g,x,y) = extgcd(K,N);
    if (S%g != 0) {
      cout << -1 << endl;
      continue;
    }
    N /= g;
    S /= g;
    K /= g;
    ll ans = ((x* -S) % N + N) % N;
    cout << ans << endl;
  }
  return 0;
}

#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
const int INF = 1001001001;
const long long LINF = 1001002003004005006;
const double PI = acos(-1);
int d4r[] = {1, 0, -1, 0};
int d4c[] = {0, 1, 0, -1};
int d8r[] = {1, 1, 0, -1, -1, -1, 0, 1};
int d8c[] = {0, 1, 1, 1, 0, -1, -1, -1};

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n; cin >> n;
    int ans = INF;
    for(int i = 0;i < n;++i) {
        int a,p,x; cin >> a >> p >> x;
        if(x - a > 0) {
            ans = min(ans,p);
        }
    }
    if(ans == INF) {
        cout << -1 << '\n';
    }
    else {
        cout << ans << '\n';
    }
    return 0;
}