高精度算法{朴素}

来源:互联网 发布:专心软件怎么签到 编辑:程序博客网 时间:2024/05/21 09:44
高精度加法:
TYPE ARR=ARRAY[1..1001] OF INTEGER;VAR  K1,K2,I:INTEGER;  S1,S2,T:ANSISTRING;  A,B,C:ARR;PROCEDURE ADD(A,B:ARR);VAR  X,I:INTEGER;BEGIN  X:=0;  FOR I:=1001 DOWNTO K1 DO    BEGIN     C[I]:=(A[I]+B[I]+X) MOD 10;     X:=(A[I]+B[I]+X) DIV 10;    END;  IF X<>0 THEN WRITE(X);  FOR I:=K1 TO 1001 DO WRITE(C[I]);END;BEGIN  READ(S1);  S2:=COPY(S1,POS(' ',S1)+1,LENGTH(S1)-POS('',S1));  DELETE(S1,POS(' ',S1),LENGTH(S1)-POS('',S1)+1);  FILLCHAR(C,SIZEOF(C),0);  IF LENGTH(S1)    BEGIN     T:=S1;     S1:=S2;     S2:=T;    END;  K1:=1001;  FOR I:=LENGTH(S1) DOWNTO 1 DO    BEGIN     VAL(S1[I],A[K1]);     DEC(K1);    END;  INC(K1);  K2:=1001;  FOR I:=LENGTH(S2) DOWNTO 1 DO    BEGIN     VAL(S2[I],B[K2]);     DEC(K2);    END;  INC(K2);  ADD(A,B);END.

高精度乘法{暂不支持负数}
type arr=array[1..1000] of integer;const maxn=1000;var  a,b,c:arr;  s1,s2:string;  i,k:longint;procedure init;var  k,i:longint;  ts:string;begin  read(s1);  s2:=copy(s1,pos(' ',s1)+1,length(s1)-pos(' ',s1));  s1:=copy(s1,1,pos(' ',s1)-1);  if length(s1)<length(s2) then    begin      ts:=s1;      s1:=s2;      s2:=s1;    end;  k:=maxn+1;  for i:=length(s1) downto 1 do    begin      dec(k);      val(s1[i],a[k]);    end;  k:=maxn+1;  for i:=length(s2) downto 1 do    begin      dec(k);      val(s2[i],b[k]);    end;end;procedure mul(a,b:arr;var c:arr);var  x,tmp:byte;  i,j,k:longint;begin  for j:=maxn downto maxn-length(s2)+1 do    begin      k:=j;      x:=0;      for i:=maxn downto maxn-length(s1)+1 do        begin          tmp:=(b[j]*a[i]+x+c[k]) mod 10;          x:=(b[j]*a[i]+x+c[k]) div 10;          c[k]:=tmp;          dec(k);        end;      if x>0 then        inc(c[k],x);    end;  if c[k]=0 then inc(k);  for i:=k to maxn do    write(c[i]);end;begin  init;  mul(a,b,c);end.

高精度除法{高精度整除低精度数}{不支持负数}
program divide{hp vs lp}type arr=array[1..1000] of integer;const maxn=1000;var  a,c:arr;  s1,s2:string;  n:longint;procedure init;var  k,i:longint;begin  read(s1);  s2:=copy(s1,pos(' ',s1)+1,length(s1)-pos(' ',s1));  val(s2,n);  s1:=copy(s1,1,pos(' ',s1)-1);  k:=maxn+1;  for i:=length(s1) downto 1 do    begin      dec(k);      val(s1[i],a[k]);    end;end;procedure divide(a,c:arr;n:longint);var  x,i,k:longint;begin  x:=0;  k:=0;  for i:=maxn-length(s1)+1 to maxn do    begin      x:=x*10+a[i];      c[i]:=x div n;      if (c[i]<>0) and (k=0) then k:=i;      x:=x mod n;    end;  for i:=k to maxn do write(c[i]);end;begin  init;  divide(a,c,n);end.


原创粉丝点击