import java.util.*;
public class Main {
// Function to find sum of AND
static List<Long> summationOfAnd(int N, List<Integer> arr, int Q, List<List<Integer>> queries) {
// Declare a 2D vector
List<List<Pair>> pref = new ArrayList<>(20);
List<List<Integer>> next = new ArrayList<>(20);
for (int i = 0; i < 20; i++) {
pref.add(new ArrayList<>(Collections.nCopies(N, new Pair(0, 0))));
next.add(new ArrayList<>(Collections.nCopies(N, 0)));
}
// Start iterating
for (int j = 0; j < 20; j++) {
int curr = 0, sum = 0;
// Iterate in array
for (int i = 0; i < N; i++) {
// Get the AND value
if ((arr.get(i) & (1 << j)) > 0) {
curr++;
sum += curr;
pref.get(j).set(i, new Pair(curr, sum));
} else {
// If curr value is greater than 0
if (curr > 0) {
next.get(j).set(i - 1, i - 1);
}
// Set the value to 0 for next iteration
curr = 0;
pref.get(j).set(i, new Pair(curr, sum));
}
}
// Update the value in next list
next.get(j).set(N - 1, N - 1);
// Start Iterating from n -2
for (int i = N - 2; i >= 0; i--) {
if (next.get(j).get(i) == 0) {
next.get(j).set(i, next.get(j).get(i + 1));
}
}
}
List<Long> ans = new ArrayList<>();
// Iterate in B
for (List<Integer> query : queries) {
int u = query.get(0) - 1;
int v = query.get(1) - 1;
long res = 0;
// Iterate again for 20 times
for (int j = 0; j < 20; j++) {
long temp;
// Get the temp value
if (u == 0) {
temp = pref.get(j).get(v).second;
} else if (pref.get(j).get(u).first == 0) {
temp = pref.get(j).get(v).second - pref.get(j).get(u).second;
} else {
// Minimum value for right
int right = Math.min(v, next.get(j).get(u));
temp = pref.get(j).get(v).second - pref.get(j).get(right).second;
if (pref.get(j).get(right).first > 0) {
temp += (right - u + 1) * (right - u + 2) / 2;
}
}
// Add the value to res
res += (temp * (1L << j));
}
// Store it in ans
ans.add(res);
}
// Return list ans
return ans;
}
// Pair class to store pair values
static class Pair {
int first;
int second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
}
// Driver code
public static void main(String[] args) {
int N = 4;
List<Integer> arr = Arrays.asList(4, 3, 2, 1);
int Q = 3;
List<List<Integer>> queries = Arrays.asList(Arrays.asList(1, 3), Arrays.asList(2, 4), Arrays.asList(1, 4));
// Function call
List<Long> ans = summationOfAnd(N, arr, Q, queries);
// Print the result
for (long a : ans) {
System.out.print(a + " ");
}
}
}