# VBA实现任意n阶幻方的一种填法(n≥3)

1568人阅读 评论(0)

Sub magicsquare(ByVal n As Long, ByRef matrix())
Dim i As Long, j As Long, k As Long, p As Long, a(), b()
ReDim matrix(1 To 256, 1 To 256)
If n < 3 Then MsgBox "n must be larger than 2! ": Exit Sub 'n不得小于3
If n Mod 4 = 0 Then '双偶阶幻方(n为偶数，且能被4整除)
ReDim a(1 To n, 1 To n)
ReDim b(1 To n, 1 To n)
For i = 1 To n
For j = 1 To n
matrix(i, j) = IIf((i Mod 4) / 2 = (j Mod 4) / 2, n * n + 1 - (i - 1) * n - j, (i - 1) * n + j)
Next
Next

Else
If n Mod 4 = 2 Then '单偶阶幻方(n为偶数，且不能被4整除)
p = n / 2
ReDim a(1 To p, 1 To p)
magicsquare p, a

For i = 1 To p
For j = 1 To p
matrix(i, j) = a(i, j)
matrix(i + p, j) = a(i, j) + 3 * p * p
matrix(i, j + p) = a(i, j) + 2 * p * p
matrix(i + p, j + p) = a(i, j) + p * p
Next
Next

For j = 1 To p
If j = p / 2 + 1 Then
For i = 1 To (n - 2) / 4
k = matrix(j, p / 2 + i)
matrix(j, p / 2 + i) = matrix(j + p, p / 2 + i)
matrix(j + p, p / 2 + i) = k
Next
Else
For i = 1 To (n - 2) / 4
k = matrix(j, i)
matrix(j, i) = matrix(j + p, i)
matrix(j + p, i) = k
Next
End If

If n > 6 Then
For i = 1 To (n - 6) / 4
k = matrix(j, p + p / 2 + i)
matrix(j, p + p / 2 + i) = matrix(j + p, p + p / 2 + i)
matrix(j + p, p + p / 2 + i) = k
Next
End If
Next

Else '奇数阶幻方

For j = 0 To n - 1
For i = 0 To n - 1
If j = 0 Then matrix(j + 1, i + 1) = IIf(i >= (n - 1) / 2, 0, n * (n + 1)) + (i - (n - 1) / 2) * (n + 2) + 1
If j > 0 Then matrix(j + 1, i + 1) = 1 + (n * n + matrix(j, i + 1) + IIf(matrix(j, i + 1) Mod n = 0, 0, n)) Mod n ^ 2
Next
Next
End If
End If
End Sub

Sub makemagicsquare()
Dim arr(), n As Long
Randomize
n = CLng(InputBox("please enter an integer", "infomation", 3 + Int(Rnd * 254)))
magicsquare n, arr
[a1].Resize(256, 256) = arr
[a1].Resize(256, 256).Columns.AutoFit
End Sub

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：631210次
• 积分：8217
• 等级：
• 排名：第2411名
• 原创：205篇
• 转载：26篇
• 译文：1篇
• 评论：213条
评论排行
最新评论