Magic squares of doubly even order: Difference between revisions
Content deleted Content added
m added highlighting, used × instead of a small "x". |
+R |
||
Line 2,111:
|64
|}
=={{header|R}}==
Translation of the magic square code example from [https://math.nist.gov/javanumerics/jama/ Jama], which is released to the public domain. This includes all three cases.
<lang R>magic <- function(n) {
if (n %% 2 == 1) {
p <- (n + 1) %/% 2 - 2
ii <- seq(n)
outer(ii, ii, function(i, j) n * ((i + j + p) %% n) + (i + 2 * (j - 1)) %% n + 1)
} else if (n %% 4 == 0) {
p <- n * (n + 1) + 1
ii <- seq(n)
outer(ii, ii, function(i, j) ifelse((i %/% 2 - j %/% 2) %% 2 == 0, p - n * i - j, n * (i - 1) + j))
} else {
p <- n %/% 2
q <- p * p
k <- (n - 2) %/% 4 + 1
a <- Recall(p)
a <- rbind(cbind(a, a + 2 * q), cbind(a + 3 * q, a + q))
ii <- seq(p)
jj <- c(seq(k - 1), seq(length.out=k - 2, to=n))
m <- a[ii, jj]; a[ii, jj] <- a[ii + p, jj]; a[ii + p, jj] <- m
jj <- c(1, k)
m <- a[k, jj]; a[k, jj] <- a[k + p, jj]; a[k + p, jj] <- m
a
}
}</lang>
'''Example'''
<pre>> magic(8)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 64 2 3 61 60 6 7 57
[2,] 9 55 54 12 13 51 50 16
[3,] 17 47 46 20 21 43 42 24
[4,] 40 26 27 37 36 30 31 33
[5,] 32 34 35 29 28 38 39 25
[6,] 41 23 22 44 45 19 18 48
[7,] 49 15 14 52 53 11 10 56
[8,] 8 58 59 5 4 62 63 1</pre>
=={{header|REXX}}==
|