SPSUM - Sum

Tác giả: flashmt

Ngôn ngữ: Pascal

type bignum=array[0..500] of longint;
var s,ss:string;
    i,l,j,k:longint;
    n,re,t,u:bignum;

procedure conv(s:string;var n:bignum);
var i:longint;
begin
     n[0]:=length(s);
     for i:=1 to n[0] do n[n[0]-i+1]:=ord(s[i])-48;
end;

procedure mul10(x:longint);
var i:longint;
begin
     for i:=t[0] downto 1 do t[i+x]:=t[i];
     for i:=x downto 1 do t[i]:=0;
     t[0]:=t[0]+x;
end;

procedure add(var a:bignum;b:bignum);
var i,mem,max:longint;
begin
     if b[0]>a[0] then max:=b[0] else max:=a[0];
     mem:=0;
     for i:=1 to max do
     begin
          a[i]:=a[i]+b[i]+mem;
          if a[i]>9 then
          begin
               a[i]:=a[i]-10; mem:=1;
          end
          else mem:=0;
     end;
     if mem>0 then
     begin
          inc(max);
          a[max]:=1;
     end;
     a[0]:=max;
end;

procedure mul(var a:bignum;x:longint);
var i,mem:longint;
begin
     mem:=0;
     for i:=1 to a[0] do
     begin
          a[i]:=a[i]*x+mem;
          mem:=a[i] div 10;
          a[i]:=a[i] mod 10;
     end;
     if mem>0 then
     begin
          inc(a[0]);
          a[a[0]]:=mem;
     end;
end;

begin
     readln(s);
     l:=length(s);
     conv(s,n);
     for i:=l downto 1 do
       for j:=1 to 9 do
       begin
            fillchar(t,sizeof(t),0);
            fillchar(u,sizeof(u),0);
            t[0]:=1; u[0]:=1;
            if i<l then
            begin
                 ss:=copy(s,1,l-i);
                 conv(ss,t);
            end;
            if j<n[i] then
            begin
                 for k:=1 to t[0]+1 do
                     if t[k]=9 then t[k]:=0
                     else
                     begin
                          inc(t[k]); break;
                     end;
                 if k>t[0] then t[0]:=k;
            end;
            if i>1 then mul10(i-1);
            if j=n[i] then
            begin
                 if i>1 then
                 begin
                      ss:=copy(s,l-i+2,i-1);
                      conv(ss,u);
                 end;
                 for k:=1 to u[0]+1 do
                     if u[k]=9 then u[k]:=0
                     else
                     begin
                          inc(u[k]); break;
                     end;
                 if k>u[0] then u[0]:=k;
                 add(t,u);
            end;
            if j>1 then mul(t,j);
            add(re,t);
       end;
     for i:=re[0] downto 1 do write(re[i]);
     writeln;
end.

Download