local n = io.read("*n") local t = {} for i = 1, n * n do t[i] = 0 end if n % 2 == 1 then local hn = math.floor(n / 2) + 1 local curh = 1 local curw = hn for i = 1, n * n do t[(curh - 1) * n + curw] = i curh = curh - 1 if curh == 0 then curh = n end curw = curw + 1 if curw == n + 1 then curw = 1 end if 0 < t[(curh - 1) * n + curw] then curh = curh + 2 if n < curh then curh = curh - n end curw = curw - 1 if curw == 0 then curw = n end end end elseif n % 4 == 0 then local k1 = {0, 1, 0, 1, 2, 3, 2, 3} local k2 = {0, 0, 1, 1, 2, 2, 3, 3} for i = 1, n do for j = 1, n do local idx = (i - 1) * n + j local ip4, jp4 = i % 4, j % 4 local f = false for k = 1, 8 do if ip4 == k1[k] and jp4 == k2[k] then f = true break end end if f then t[idx] = idx else t[idx] = n * n + 1 - idx end end end else local b = {} local tn = math.floor(n / 2) for i = 1, tn * tn do b[i] = 0 end local hn = math.floor(tn / 2) + 1 local curh = 1 local curw = hn for i = 1, tn * tn do b[(curh - 1) * tn + curw] = i curh = curh - 1 if curh == 0 then curh = tn end curw = curw + 1 if curw == tn + 1 then curw = 1 end if 0 < b[(curh - 1) * tn + curw] then curh = curh + 2 if tn < curh then curh = curh - tn end curw = curw - 1 if curw == 0 then curw = tn end end end for i = 1, tn * tn do b[i] = (b[i] - 1) * 4 end for i = 1, tn do for j = 1, tn do if i < hn or (i == hn and j ~= hn) or (i == hn + 1 and j == hn) then t[(i - 1) * 2 * n + j * 2 - 1] = b[(i - 1) * tn + j] + 4 t[(i - 1) * 2 * n + j * 2 - 0] = b[(i - 1) * tn + j] + 1 t[(i - 1) * 2 * n + n + j * 2 - 1] = b[(i - 1) * tn + j] + 2 t[(i - 1) * 2 * n + n + j * 2 - 0] = b[(i - 1) * tn + j] + 3 elseif i <= hn + 1 then t[(i - 1) * 2 * n + j * 2 - 1] = b[(i - 1) * tn + j] + 1 t[(i - 1) * 2 * n + j * 2 - 0] = b[(i - 1) * tn + j] + 4 t[(i - 1) * 2 * n + n + j * 2 - 1] = b[(i - 1) * tn + j] + 2 t[(i - 1) * 2 * n + n + j * 2 - 0] = b[(i - 1) * tn + j] + 3 else t[(i - 1) * 2 * n + j * 2 - 1] = b[(i - 1) * tn + j] + 1 t[(i - 1) * 2 * n + j * 2 - 0] = b[(i - 1) * tn + j] + 4 t[(i - 1) * 2 * n + n + j * 2 - 1] = b[(i - 1) * tn + j] + 3 t[(i - 1) * 2 * n + n + j * 2 - 0] = b[(i - 1) * tn + j] + 2 end end end end for i = 1, n do for j = 1, n do io.write(t[(i - 1) * n + j]) io.write(j == n and "\n" or " ") end end local ast = math.floor(n * (n * n + 1) / 2) for i = 1, n do local c = 0 for j = 1, n do c = c + t[(i - 1) * n + j] end assert(ast == c) end for j = 1, n do local c = 0 for i = 1, n do c = c + t[(i - 1) * n + j] end assert(ast == c) end do local c = 0 for i = 1, n do c = c + t[(i - 1) * n + i] end assert(ast == c) end do local c = 0 for i = 1, n do c = c + t[(i - 1) * n + n + 1 - i] end assert(ast == c) end