#include "bits/stdc++.h" using namespace std; #define FOR(i,j,k) for(int (i)=(j);(i)<(int)(k);++(i)) #define rep(i,j) FOR(i,0,j) #define each(x,y) for(auto &(x):(y)) #define mp make_pair #define all(x) (x).begin(),(x).end() #define debug(x) cout<<#x<<": "<<(x)< pii; typedef vector vi; typedef vector vll; string nstr(){ static const int MAX_LEN = 1000000; static char res_[MAX_LEN]; scanf("%s",res_); return string(res_); } template map factorize(Val n){ map res; for(Val i=2; (long long)i*i<=n; ++i){ while(n%i==0){ n /= i; ++res[i]; } } if(n!=1) ++res[n]; return res; } int powMod(int n, int k, int mod){ if(n==0)return 0; ll res = 1 % mod, nn = n; while(k){ if(k&1)res=res*nn%mod; nn=nn*nn%mod; k>>=1; } return (int)res; } string S; void solve() { int N = sz(S), ans = 0; if(count(all(S), '0') == N) { puts("0"); return; } map c; rep(i, N) { if(i != 0) { map a = factorize<>(N - i), b = factorize<>(i); each(p, a)c[p.first] += p.second; vi r; each(p, b) { c[p.first] -= p.second; if(c[p.first] == 0) { r.push_back(p.first); } } each(x, r)c.erase(x); } int x = 1; each(p, c)(x *= powMod(p.first, p.second, 9))%=9; (ans += x * (S[i]-'0')) %= 9; } if(ans == 0)ans = 9; printf("%d\n", ans); } int main(){ int T; cin >> T; while(T--) { S = nstr(); solve(); } }