R/odd_magic_square.R

Defines functions odd_magic_square

Documented in odd_magic_square

#' Construct odd order magic square (Siamese method)
#'
#' @param k Odd order number
#'
#' @return k x k magic square with numbers 1 to k^2
#' @export
#'
#' @examples
#' odd_magic_square(7)

odd_magic_square <- function(k) {
  if (k %% 2 == 0) stop("k must be an odd number")
  M <- matrix(0, nrow = k, ncol = k)
  i <- 1
  j <- (k + 1) / 2
  for (num in 1:(k^2)) {
    M[i, j] <- num
    i_next <- i - 1
    j_next <- j + 1
    if (i_next < 1) i_next <- k
    if (j_next > k) j_next <- 1
    if (M[i_next, j_next] != 0) {
      i_next <- i + 1
      j_next <- j
    }
    i <- i_next
    j <- j_next
  }
  M
}

Try the YangHuiMagic package in your browser

Any scripts or data that you put into this service are public.

YangHuiMagic documentation built on March 23, 2026, 5:07 p.m.