PCIRCLE - Vòng số nguyên tố

Tác giả: RR

Ngôn ngữ: Pascal

const
  res:array[2..9] of longint=(2,2,4,96,1024,2880,81024,770144);
var
  used,p:array[1..40] of boolean;
  a:array[1..40] of longint;
  cnt,n,i:longint;

function isPrime(n:longint):boolean;
    var
      i:longint;
    begin
      for i:=2 to trunc(sqrt(n)) do
        if n mod i=0 then exit(false);
      exit(i>1);
    end;

procedure dequy(i:longint);
    var
      j,k:longint;
    begin
      if cnt>10000 then exit;
      for j:=2 to n shl 1 do
      if (not used[j]) and p[a[i-1]+j] then
        begin
          used[j]:=true;
          a[i]:=j;
          if i<n shl 1 then dequy(i+1)
          else if p[a[1]+a[i]] then
            begin
              inc(cnt);
              if cnt>10000 then exit;
              for k:=1 to n shl 1 do write(a[k],' ');
              writeln;
            end;
          used[j]:=false;
          if cnt>10000 then exit;
        end;
    end;

begin
  fillchar(used,sizeof(used),false);
  for i:=1 to 40 do p[i]:=isPrime(i);
  a[1]:=1; used[1]:=true;
  read(n); writeln(res[n]);
  dequy(2);
end.

Download