How to resolve the algorithm Magic squares of odd order step by step in the Icon and Unicon programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Magic squares of odd order step by step in the Icon and Unicon programming language
Table of Contents
Problem Statement
A magic square is an NxN square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, and both long (main) diagonals are equal to the same sum (which is called the magic number or magic constant). The numbers are usually (but not always) the first N2 positive integers. A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.
For any odd N, generate a magic square with the integers 1 ──► N, and show the results here.
Optionally, show the magic number.
You should demonstrate the generator by showing at least a magic square for N = 5.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Magic squares of odd order step by step in the Icon and Unicon programming language
Source code in the icon programming language
procedure main(A)
n := integer(!A) | 3
write("Magic number: ",n*(n*n+1)/2)
sq := buildSquare(n)
showSquare(sq)
end
procedure buildSquare(n)
sq := [: |list(n)\n :]
r := 0
c := n/2
every i := !(n*n) do {
/sq[r+1,c+1] := i
nr := (n+r-1)%n
nc := (c+1)%n
if /sq[nr+1,nc+1] then (r := nr,c := nc) else r := (r+1)%n
}
return sq
end
procedure showSquare(sq)
n := *sq
s := *(n*n)+2
every r := !sq do every writes(right(!r,s)|"\n")
end
You may also check:How to resolve the algorithm Arithmetic/Integer step by step in the RPL programming language
You may also check:How to resolve the algorithm Arithmetic/Integer step by step in the MUMPS programming language
You may also check:How to resolve the algorithm Zeckendorf number representation step by step in the Arturo programming language
You may also check:How to resolve the algorithm Pick random element step by step in the Logo programming language
You may also check:How to resolve the algorithm Floyd's triangle step by step in the Delphi programming language