reserve x, x1, x2, y, X, D for set,
  i, j, k, l, m, n, N for Nat,
  p, q for XFinSequence of NAT,
  q9 for XFinSequence,
  pd, qd for XFinSequence of D;

theorem Th25:
  for p,n st rng p c= {0,n} ex q st len p = len q & rng q c= {0,n}
  & (for k st k <= len p holds Sum (p|k)+Sum (q|k) = n*k) & for k st k in len p
  holds q.k = n-p.k
proof
  let p,n such that
A1: rng p c= {0,n};
reconsider nn=n as Element of NAT by ORDINAL1:def 12;
  defpred P[set,set] means for k st k=$1 holds $2=n-p.k;
A2: for k st k in Segm len p ex x be Element of {0,n} st P[k,x]
  proof
    let k;
    assume k in Segm len p;
    then p.k in rng p by FUNCT_1:3;
    then p.k=0 or p.k=n by A1,TARSKI:def 2;
    then
A3: n-p.k in {0,n} by TARSKI:def 2;
    P[k,n-p.k];
    hence thesis by A3;
  end;
  consider q be XFinSequence of {0,n} such that
A4: dom q= Segm len p& for k st k in Segm len p holds P[k,q.k]
   from STIRL2_1:sch 5(A2);
  reconsider q as XFinSequence of NAT;
  defpred Q[Nat] means $1 <= len p implies Sum (p|$1)+ Sum (q|$1)=n*$1;
A5: for k st Q[k] holds Q[k+1]
  proof
    let k such that
A6: Q[k];
    set k1=k+1;
A7: k<k+1 by NAT_1:13;
    then
A8: Segm k c= Segm(k+1) by NAT_1:39;
    then
A9: (p|k1)|k=p|k by RELAT_1:74;
A10: (q|k1)|k=q|k by A8,RELAT_1:74;
    assume
A11: k+1 <= len p;
    then
A12: Segm k1 c= Segm len p by NAT_1:39;
    then
A13: len (q|k1)=k1 by A4,RELAT_1:62;
    then
A14: (q|k1)=((q|k1)|k)^<%(q|k1).k%> by AFINSQ_1:56;
    len (p|k1)=k1 by A12,RELAT_1:62;
    then
A15: k in dom (p|k1) by A7,AFINSQ_1:86;
    then
A16: (p|k1).k= p.k by FUNCT_1:47;
 len (p|k1)=k1 by A12,RELAT_1:62;
    then (p|k1)=((p|k1)|k)^<%(p|k1).k%> by AFINSQ_1:56;
    then Sum (p|k1)=Sum (p|k)+Sum <%p.k%> by A16,A9,AFINSQ_2:55;
    then
A17: Sum (p|k1)=Sum (p|k)+p.k by AFINSQ_2:53;
    k< len p by A11,NAT_1:13;
    then k in len p by AFINSQ_1:86;
    then
A18: q.k=n-p.k by A4;
    (q|k1).k= q.k by A13,A15,FUNCT_1:47;
    then Sum (q|k1)=Sum (q|k)+Sum <%q.k%> by A14,A10,AFINSQ_2:55;
    then Sum (q|k1)=Sum (q|k)+ (n-p.k) by A18,AFINSQ_2:53;
    hence thesis by A6,A11,A17,NAT_1:13;
  end;
  take q;
  thus len p=len q by A4;
  thus rng q c= {0,n} by RELAT_1:def 19;
A19: Q[0];
  for k holds Q[k] from NAT_1:sch 2(A19,A5);
  hence thesis by A4;
end;
