// Arup Guha
// 6/1/2015
// Solution to Prog Comp Camp Contest #1 Problem: Calculator Games

import java.util.*;

public class calc_arup {

    final public static int MOD = 1000000;

    public static void main(String[] args) {

        Scanner stdin = new Scanner(System.in);
        int numCases = stdin.nextInt();

        // Process each case.
        for (int loop=0; loop<numCases; loop++) {

            // Get input parameters.
            int a = stdin.nextInt();
            int b = stdin.nextInt();
            int c = stdin.nextInt();
            int target = stdin.nextInt();

            // Set up BFS.
            LinkedList<Integer> q = new LinkedList<Integer>();
            int[] dist = new int[MOD];
            Arrays.fill(dist, -1);
            dist[0] = 0;
            q.offer(0);

            // Do BFS.
            while (q.size() > 0) {

                // We already have our answer, get out!
                if (dist[target] != -1) break;

                // Get next item.
                int cur = q.poll();

                // Store next candidates.
                ArrayList<Integer> next = new ArrayList<Integer>();
                next.add((cur+a)%MOD);
                next.add((cur*b)%MOD);
                next.add(cur/c);

                // Queue them, if necessary.
                for (int i=0; i<next.size(); i++) {
                    if (dist[next.get(i)] == -1) {
                        q.offer(next.get(i));
                        dist[next.get(i)] = dist[cur] + 1;
                    }
                }

            } // end bfs.

            // Here is the result.
            System.out.println(dist[target]);
        }
    }
}
