#include <iostream>
#define endl '\n'
using namespace std;

int rule(long long n) {
    long long sum = 0;
    long long digit;

    while (n > 0) {
        digit = n%10;
        sum += digit*digit;
        n /= 10;
    }

    return sum;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    long long T;
    cin >> T;

    for (long long t = 0, a, v, n; t < T; t++) {
        cin >> a >> v >> n;

        long long total = 0;
        if (a == v) total++;

        long long next = a;
        long long repeat = -1;
        long long members = 0;

        bool visited[649] = {false};

        for (long long i = 1; i < n; i++) {
            next = rule(next);

            members++;
            if (next == v) total++;

            if (visited[next] == true) {
                repeat = next;
                break;
            } else if (next == a) {
                repeat = a;
                break;
            } else {
                visited[next] = true;
            }
        }

        if (repeat != -1) {
            if (repeat == a) {
                if (repeat == v) total--;
                total *= n/members;
                if (n%members != 0) {
                    for (long long i = 0, last = repeat; i < n%members; i++) {
                        if (last == v) total++;
                        last = rule(last);
                    }
                }
            } else if (repeat == v) {
                total--;
                long long temp = a;
                long long withdrawMembers = 0;
                while (temp != repeat) {
                    members--;
                    withdrawMembers++;
                    temp = rule(temp);
                }
                total *= (n - withdrawMembers)/members;
                if (n%members != 0) {
                    for (long long i = 0, last = repeat; i < (n - withdrawMembers)%members; i++) {
                        if (last == v) total++;
                        last = rule(last);
                    }
                }
            } else {
                long long temp = a;
                long long withdrawMembers = 0;
                long long vBeforeRep = 0;
                while (temp != repeat) {
                    withdrawMembers++;
                    if (temp == v) {
                        vBeforeRep++;
                    }
                    temp = rule(temp);
                }
                total -= vBeforeRep;
                total *= (n - withdrawMembers)/members;
                if (n%members != 0) {
                    for (long long i = 0, last = repeat; i < (n - withdrawMembers)%members; i++) {
                        if (last == v) total++;
                        last = rule(last);
                    }
                }
                total += vBeforeRep;
            }
        }

        cout << total << endl;
    }

    return 0;
}
