


Let N = 3 and M = 5
The number of squares of size 1 will be 15.
The number of squares of size 2 will be 8.
The number of squares of size 3 will be 3.
Thus the answer will be 26.
The first line of input contains an integer ‘T’ denoting the number of test cases.
The first and only line of each test case contains two space seperated integers N and M denoting the dimensions of the matrix.
For each test case, return an integer denoting the count of squares in the matrix modulo 10^9 + 7.
Don’t print anything, just return the count of squares in the matrix modulo 10^9 + 7.
1 <= T <= 10^5
1 <= N <= 10^9
1 <= M <= 10^9
Time limit: 1 sec
The brute force approach is to count the number of squares of each size
A better approach would be generating a formula to count the number of squares.
The number of squares in a matrix of size N * N will be ∑ (N - i)^2 or ∑ i^2 which is equal to (N (N+1) (2N + 1)) / 6.
Now if we try to insert a column the matrix will be of size N * (N + 1). Now let’s count how many new squares are possible.
So the number of new squares will be ∑ (N - i) or ∑ i which is equal to (N (N+1))/2.
Now, we need to add M - N new columns to get the matrix of size N * M.
Thus, total no of squares will be:
(N (N+1) (2N + 1)) / 6 + (N (M-N) (N + 1)) / 2
Solving further we get:
(N (N+1) (3M-N+1)) / 6
Note: Here we assumed that M is greater than N. If M is smaller than N, then swap N and M.