magic_square(3f) - [M_math] create an N x N magic square array, N>2
Synopsis
Description
Options
Author
Example
subroutine magic_square(array)
class(*) :: array
This procedure returns a magic squares array, an n by n matrix in which each integer 1, 2, ..., n*n appears exactly once; and all columns, rows, and diagonals sum to the same number.
array An array to fill with the magic square values. The smallest dimension should be >= 3. Since a square is required only the values array(1:n,1:n) will be filled, where n=min(rows,columns). The array may be INTEGER, REAL, or DOUBLEPRECISION.
Note that the routine allocates an integer array of the size determined by the input routine during execution.
John S. UrbanBased on an algorithm for magic squares from
Mathematical Recreations and Essays, 12th ed., by W. W. Rouse Ball and H. S. M. Coxeter
Sample program
program demo_magic_square use M_math, only : magic_square implicit none integer :: arr(15,15) integer :: i, j, k do k=1,15 write(*,*)K=,k call magic_square(arr(:k,:k)) do i=1,k write(*,(i2,":",*(i5):))i,(int(arr(i,j)),j=1,k),sum(arr(k,:k)) enddo enddo end program demo_magic_square
Nemo Release 3.1 | magic_square (3) | February 23, 2025 |