#include "bits/stdc++.h"
// #pragma GCC optimize("O3,unroll-loops")
// #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
using namespace std;
using ll = long long int;
mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().count());

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

	int t; cin >> t;
	while (t--) {
		int n; cin >> n;
		vector<int> a(n), b(n);
		array<int, 20> allct{}, hsbct{};
		array<array<int, 20>, 20> bitct{};
		ll sumB = 0;
		for (int &x : a) cin >> x;
		for (int &x : b) {
			cin >> x;
			sumB += x;
			if (x == 0) continue;
			int hsb = 20;
			while (~x&(1<<hsb)) --hsb;
			++hsbct[hsb];
			for (int i = 0; i < 20; ++i) {
				allct[i] += (x>>i)&1;
				bitct[hsb][i] += (x>>i)&1;
			}
		}
		sort(rbegin(a), rend(a));
		ll ans = 0;
		int hsb = 20;
		for (int x : a) {
			if (x == 0) {
				ans += sumB;
				continue;
			}
			while (~x&(1<<hsb)) --hsb;
			
			// Same hsb -> AND
			for (int bit = 0; bit < 20; ++bit) {
				if (~x & (1<<bit)) continue;
				ans += (1LL<<bit) * bitct[hsb][bit]; 
			}

			// Different hsb -> XOR
			for (int bit = 0; bit < 20; ++bit) {
				int ct = 0;
				if (x & (1<<bit)) ct = n - allct[bit] - (hsbct[hsb] - bitct[hsb][bit]);
				else ct = allct[bit] - bitct[hsb][bit];
				ans += (1LL<<bit) * ct;
			}
		}
		cout << ans << '\n';
	}
}