A Note on a Math Magic Trick

Introduction

I came across this Quora article, Math Magic Trick, and I was intrigued by the following statement:

Given the 4-by-4 matrix

$$ {\boldsymbol A}_4= \left[ \begin{array}{rrrr} 1 & 2 & 3 & 4\\ 5 & 6 & 7 & 8\\ 9 & 10 & 11 & 12\\ 13 & 14 & 15 & 16 \end{array} \right], $$

if we choose any four elements that lie in different rows and columns of $ {\boldsymbol A}_4 $, then the sum of the chosen elements is equal to 34. This is interesting!

In this note, I will first generalize the above statement to an $ n $ by $ n $ matrix and encapsulate the result in a proposition. Next, I will provide a proof of the proposition. Finally, I will write some R code (for practice purposes) to verify the original statement from the Quora article, Math Magic Trick.

Generalization

Proposition: For any positive integer $ n $, define the matrix

$$ {\boldsymbol A}_n= \left[ \begin{array}{rrrr} 1 & 2 & \cdots & n\\ n+1 & n+2 & \cdots & 2n\\ \vdots & \vdots & \cdots & \vdots\\ (n-1)n+1 & (n-1)n+2 & \cdots & n^2 \end{array} \right]. $$

If we choose any $ n $ elements from $ {\boldsymbol A}_n $ such that no two chosen elements lie in the same row or the same column, then the sum of the chosen elements is

$$ \frac{n(n^2+1)}{2}. $$

Proof. Denote

$$ {\boldsymbol A}_n := (a_{ij}). $$

Then

$$ a_{ij} = 1 + (i-1)n + j-1 = (i-1)n + j, $$

where $ 1\le i\le n $ and $ 1\le j\le n $. Let $ s $ denote the sum of any $ n $ elements chosen from $ {\boldsymbol A}_n $ that satisfy the condition that no two chosen elements lie in the same row or column. Since exactly one element is chosen from each row and each column,

$$ \begin{array}{ccl} s &=& \sum_{i=1}^n (i-1)n + \sum_{j=1}^n j\\ &=& \frac{n(n^2+1)}{2}. \end{array} $$

This completes the proof.

R code: an exercise

check_sum <- function(n = 4)
{the_sum <- n * (n^2 + 1) / 2

 A <- matrix(1:n^2, ncol = n, byrow = TRUE)
 
 # permutations 
 perm <- gtools::permutations(n = n, r = n, v = 1:n)
 
 # number of permutations
 m <- dim(perm)[1]
 
 # a vector to store all the sums
 s <- vector(mode = 'integer', length = m)
 for(i in seq_len(m)) {
   s[i] <- sum(A[cbind(1:n, perm[i, ])])
 }
 
 chk <- all(s == the_sum)
 
 if(chk) {cat(sprintf("All the %d sums are %d.", m, the_sum))} else {
   cat("Something is wrong!")}
}

check_sum(n = 4)
## All the 24 sums are 34.
check_sum(n = 5)
## All the 120 sums are 65.
check_sum(n = 6)
## All the 720 sums are 111.
Lingyun Zhang (张凌云)
Lingyun Zhang (张凌云)
Design Analyst

I have research interests in Statistics, applied probability and computation.