about summary refs log tree commit diff
path: root/12/TP-HN-2009/R2/BAI1.PAS
blob: b28ae0b47f0cfd08b2d34a374b45b7ca7418279a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
uses math;

var
  f : text;
  n : longint;
  lena, i : integer;
  a : array[1..512] of longint;

procedure insort(x : longint);
  var i, j : integer;
  begin
    inc(lena);
    a[lena] := x - 1;
    for i := 1 to lena do
      if a[i] < x then begin
        for j := lena downto i + 1 do
          a[j] := a[j - 1];
        a[i] := x;
        exit
      end
  end;

function notin(x : longint) : boolean;
  var l, h, m : integer;
  begin
    l := 1;
    h := lena;
    repeat
      m := (l + h) div 2;
      if a[m] = x then exit(false);
      if a[m] < x then h := m - 1
      else l := m + 1
    until l > h;
    notin := true
  end;

procedure mklist(n0 : longint);
  var
    i, j : byte;
    n10, m0 : longint;
  begin
    if n0 <> 0 then begin
      insort(n0);
      for i := 0 to trunc(log10(n0)) do
        begin
          n10 := 1;
          for j := 1 to i do n10 := n10 * 10;
          m0 := n0 div (n10 * 10) + n0 mod n10;
          if notin(m0) then mklist(m0)
        end
    end
  end;

function prime(m : longint) : boolean;
  var p, q : integer;
  begin
    if m < 2 then exit(false);
    if m = 2 then exit(true);
    if m = 3 then exit(true);
    if m mod 2 = 0 then exit(false);
    if m mod 3 = 0 then exit(false);
    p := 5;
    q := 2;
    while p * p <= m do
      begin
        if m mod p = 0 then exit(false);
        p := p + q;
        q := 6 - q
      end;
    prime := true
  end;

begin
  assign(f, 'BAI1.INP');
  reset(f);
  read(f, n);
  close(f);
  lena := 0;
  mklist(n);
  assign(f, 'BAI1.OUT');
  rewrite(f);
  for i := 1 to lena do
    if prime(a[i]) then begin
      writeln(f, a[i]);
      close(f);
      exit
    end;
  writeln(f, -1);
  close(f)
end.