#include <bits/stdc++.h>
using namespace std;
#define file(NAME) if (fopen(NAME".inp", "r")) freopen(NAME".inp", "r", stdin), freopen(NAME".out", "w", stdout)
#define FOR(i, a, b) for (int i = (int) a; i <= (int) b; ++i)
#define FOD(i, a, b) for (int i = (int) a; i >= (int) b; --i)
#define all(s) (s).begin(), (s).end()
#define pb push_back
#define ll long long
#define fi first
#define se second
#define pii pair<int, int>
const int maxn = 1e5 + 5;
const int N = 505;
const int MOD = 1e9 + 7;
int x, v, n;
int change(int n) {
if (!n) return 0;
return ((n % 10) * (n % 10) + change(n / 10));
}
void solve() {
cin >> x >> v >> n;
vector<int> circle;
unordered_map<int, int> freq, freq1;
while (true) {
freq[x]++;
// cerr << x << ' ';
circle.pb(x);
if (freq[x] == 2) break;
x = change(x);
}
int cur = 0;
vector<int> tmp;
for (int i = 0; i < circle.size(); ++i) {
if (freq[circle[i]] == 2) {
--freq[circle[i]];
cur = i; break;
}
tmp.pb(circle[i]);
--freq[circle[i]];
++freq1[circle[i]];
}
int len2 = circle.size() - 1 - cur;
int len1 = tmp.size();
ll ans = 0;
if (n <= len1) {
if (freq1[v] == 0) ans = 0;
else for (int i = 0; i < n; ++i) {
if (tmp[i] == v) {
ans = 1; break;
}
}
}
else {
n -= len1;
ans += freq1[v];
ans += (freq[v] * (n / len2));
FOR(i, cur, cur + (n % len2) - 1) {
if (circle[i] == v) {
++ans; break;
}
}
}
cout << ans << '\n';
}
int Test;
signed main() {
cin.tie(0) -> sync_with_stdio(0);
file("x");
cin >> Test;
while (Test--) solve();
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+Cgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKI2RlZmluZSBmaWxlKE5BTUUpIGlmIChmb3BlbihOQU1FIi5pbnAiLCAiciIpKSAgZnJlb3BlbihOQU1FIi5pbnAiLCAiciIsIHN0ZGluKSwgZnJlb3BlbihOQU1FIi5vdXQiLCAidyIsIHN0ZG91dCkKI2RlZmluZSBGT1IoaS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pcmNsZVtpXV07CiAgICAgICAgICAgIGN1ciA9IGk7IGJyZWFrOwogICAgICAgIH0KICAgICAgICB0bXAucGIoY2lyY2xlW2ldKTsKICAgICAgICAtLWZyZXFbY2lyY2xlW2ldXTsKICAgICAgICArK2ZyZXExW2NpcmNsZVtpXV07CiAgICB9CgogICAgaW50IGxlbjIgPSBjaXJjbGUuc2l6ZSgpIC0gMSAtIGN1cjsKCgogICAgaW50IGxlbjEgPSB0bXAuc2l6ZSgpOwoKCgogICAgbGwgYW5zID0gMDsKICAgIGlmIChuIDw9IGxlbjEpIHsKICAgICAgICBpZiAoZnJlcTFbdl0gPT0gMCkgYW5zID0gMDsKICAgICAgICBlbHNlIGZvciAoaW50IGkgPSAwOyBpIDwgbjsgKytpKSB7CiAgICAgICAgICAgIGlmICh0bXBbaV0gPT0gdikgewogICAgICAgICAgICAgICAgYW5zID0gMTsgYnJlYWs7CiAgICAgICAgICAgIH0KICAgICAgICB9CiAgICB9CiAgICBlbHNlIHsKICAgICAgICBuIC09IGxlbjE7CiAgICAgICAgYW5zICs9IGZyZXExW3ZdOwogICAgICAgIAogICAgICAgIGFucyArPSAoZnJlcVt2XSAqIChuIC8gbGVuMikpOwoKICAgICAgICBGT1IoaSwgY3VyLCBjdXIgKyAobiAlIGxlbjIpIC0gMSkgewogICAgICAgICAgICBpZiAoY2lyY2xlW2ldID09IHYpIHsKICAgICAgICAgICAgICAgICsrYW5zOyBicmVhazsKICAgICAgICAgICAgfQogICAgICAgIH0KICAgIH0KCgoKICAgIGNvdXQgPDwgYW5zIDw8ICdcbic7Cn0KCgoKCgoKCmludCBUZXN0OwpzaWduZWQgbWFpbigpIHsKICAgIGNpbi50aWUoMCkgLT4gc3luY193aXRoX3N0ZGlvKDApOwogICAgZmlsZSgieCIpOwogICAgCiAgICAKICAgIAogICAgY2luID4+IFRlc3Q7CiAgICB3aGlsZSAoVGVzdC0tKSBzb2x2ZSgpOwogICAgCiAgICByZXR1cm4gMDsKfQo=