n, *is = $<.read.split(/\s+/).map(&:to_i)
min = n
(1..n).each{|w|
    a = is.map{|i| [(i-1) % w, (i-1) / w]}
    sum = (0..3).map{|i| (a[i&2][i%2] - a[1+(i&2)][i%2]).abs}.inject(&:+)
    min = [min, sum].min
}
puts min