1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <algorithm> 6 #include <queue> 7 #include <vector> 8 #include <stack> 9 #include <map> 10 #include <set> 11 #include <cmath> 12 #include <cctype> 13 #include <ctime> 14 15 using namespace std; 16 17 #define REP(i, n) for (int i = 0; i < (n); ++i) 18 #define eps 1e-9 19 20 typedef long long ll; 21 typedef pair<int, int> pii; 22 23 const int INF = 0x7fffffff; 24 const int maxn = 100; 25 int T; 26 ll n, k; 27 28 ll cal1() { 29 if (n % 4 == 1) { return 1; } 30 if (n % 4 == 2) { return n + 1; } 31 if (n % 4 == 3) { return 0; } 32 return n; 33 } 34 ll cal2() { 35 ll ret = n, s = 1, n_t = n - 1, t_1 = 1, t_2 = 0, l, r, t1, t2; 36 while (n_t) { 37 ret ^= s; 38 l = (n_t - 1) / k * k + 1; r = l + k - 1; 39 t1 = n_t - l; t2 = r - n_t; 40 s += t_1 * t1 + t_2 * t2 + 1; 41 if (t1 % 2 == 1) { ret ^= t_1; } t_1 = t_1 * k + 1; 42 if (t2 % 2 == 1) { ret ^= t_2; } t_2 = t_2 * k + 1; 43 n_t = (n_t - 1) / k; 44 } 45 return ret; 46 } 47 48 int main() { 49 #ifdef __AiR_H 50 freopen("in.txt", "r", stdin); 51 // freopen("out.txt", "w", stdout); 52 #endif // __AiR_H 53 scanf("%d", &T); 54 while (T--) { 55 scanf("%I64d %I64d", &n, &k); 56 if (k == 1) { printf("%I64d ", cal1()); continue; } 57 printf("%I64d ", cal2()); 58 } 59 #ifdef __AiR_H 60 printf("Time used = %.2fs ", (double)clock() / CLOCKS_PER_SEC); 61 #endif // __AiR_H 62 return 0; 63 }