program skaiciu_grupes;
  { 13 u‘davinys }
  var N,  { duotasis skai‡ius }
      N2, { jo kvadratas }
      sk, { eilinis d‚muo }
      s,  { eilut‚s suma }
      i, j : integer;
  function succ_sk (N2, sk, z : integer) : integer;
    { ratu  priek nuo sk per z skai‡i— }
  begin
    if sk + z > N2
       then succ_sk := sk + z - N2
       else succ_sk := sk + z
  end;
  function pred_sk (N2, sk, z : integer) : integer;
    { ratu atgal nuo sk per z skai‡i— }
  begin
    if sk >= z
       then pred_sk := sk - z
       else pred_sk := sk + N2 - z
  end;
begin
  write ('­veskite skai‡i— N: ');
  readln (n);
  sk := 1;
  N2 := N * N;  { pradin‚s reikžm‚s }
  for i := 1 to N do { N eilu‡i— }
    begin
      s := 0; { sumuosime N - 1 d‚men }
      for j := 1 to N - 1 do
        begin
          write (sk : 4); { spausdiname eilut‚s nar }
          s := s + sk;
          sk := succ_sk (N2, sk, N + 1) { randame kit… nar }
        end;
      write (sk : 4);  { spausdiname paskutinj eilut‚s nar }
      s := s + sk;
      writeln (s : 6);  { spausdiname eilut‚s sum… }
      sk := pred_sk (N2, sk, N - 1) { randame kitos eilut‚s pirm…j nar }
    end
end.
