#include #include using namespace std; const int MAX_N = 10000001; // (3n)! = 3^thress[n]k (kは3の倍数ではない) vector threes; vector fact; vector inv; void init() { threes.resize((MAX_N + 2) / 3); threes[0] = 0; for(size_t i = 1; i < threes.size(); i++) { size_t j = i * 3; threes[i] = threes[i - 1]; while(j % 3 == 0) { threes[i]++; j /= 3; } } fact.resize(MAX_N); fact[0] = 1; for(size_t i = 1; i < fact.size(); i++) { int j = i; while(j % 3 == 0) j /= 3; fact[i] = (fact[i - 1] * j) % 9; } inv.resize(9); for(int i = 0; i < 9; i++) { for(int j = 0; j < 9; j++) { if(i * j % 9 == 1) inv[i] = j; } } } int comb(int n, int k) { int t = threes[n/3] - threes[(n - k) / 3] - threes[k / 3]; if(t >= 2) return 0; int ret = fact[n] * inv[fact[n - k]] * inv[fact[k]] % 9; if(t == 1) ret = ret * 3 % 9; return ret; } int main() { init(); int T; cin >> T; string S; for(int i = 0; i < T; i++) { cin >> S; bool allzero = true; int ans = 0; for(int i = 0; i < S.size(); i++) { ans = (ans + (S[i] - '0') * comb(S.size() - 1, i)) % 9; if(S[i] != '0')allzero = false; } ans %= 9; if(ans == 0 && !allzero) ans = 9; cout << ans << endl; } }