V. High precision calculation
Definition of high precision:
Type
HP = array [1..maxlen] of integer;
1. High precision addition
Procedure Plus (A, B: Hp; Var C: HP);
VAR I, LEN: Integer;
Begin
Fillchar (C, SizeOf (C), 0);
IF a [0]> b [0] THEN LEN: = a [0] else len: = b [0];
For i: = 1 to len do begin
INC (C [I], A [I] B [I]);
IF C [I]> 10 THEN BEGIN DEC (C [I], 10); INC (C [i 1]); end; {carry}
END;
IF C [LEN 1]> 0 THEN INC (LEN);
C [0]: = LEN;
End; {plus}
2. High precision subtraction
Procedure Substract (A, B: HP; VAR C: HP);
VAR I, LEN: Integer;
Begin
Fillchar (C, SizeOf (C), 0);
IF a [0]> b [0] THEN LEN: = a [0] else len: = b [0];
For i: = 1 to len do begin
INC (C [I], A [I] -B [I]);
IF C [I] <0 THEN BEGIN INC (C [I], 10); DEC (C [i 1]);
While (LEN> 1) AND (C [LEN] = 0) DO DEC (LEN);
C [0]: = LEN;
END;
3. High precision multiplied by low accuracy
Procedure Multiply (a: hp; b: longint; var C: HP);
VAR I, LEN: Integer;
Begin
Fillchar (C, SizeOf (C), 0);
Len: = a [0];
For i: = 1 to len do begin
INC (C [I], A [I] * b);
INC (C [i 1], (a [i] * b) DIV 10);
C [i]: = C [i] mod 10;
END;
Inc.;
While (C [LEN]> = 10) Do Begin {Treat the highest position}
C [LEN 1]: = C [LEN] DIV 10;
C [LEN]: = C [LEN] MOD 10;
Inc.;
END;
While (LEN> 1) AND (C [LEN] = 0) Do Dec (LEN); {If you don't need to carry, adjust the len}
C [0]: = LEN;
End; {Multiply}
4. High precision multiplied by high precision
Procedure high_multiply (a, b: hp; var c: hp}
Var i, j, len: integer;
Begin
Fillchar (C, SizeOf (C), 0);
For i: = 1 to a [0] DO
For j: = 1 to b [0] do begin
INC (C [i J-1], A [I] * B [J]);
INC (C [i J], C [i J-1] DIV 10);
C [i j-1]: = C [i j-1] mod 10;
END;
Len: = a [0] b [0] 1;
While (LEN> 1) AND (C [LEN] = 0) DO DEC (LEN);
C [0]: = LEN;
END;
5. High precision dividend
Procedure devide (a: hp; b: longint; var c: hp; var d: longint);
{C: = a DIV B; D: = a mod b} var i, len: integer;
Begin
Fillchar (C, SizeOf (C), 0);
LEN: = a [0]; D: = 0;
For i: = len downto 1 do begin
D: = D * 10 a [i];
C [I]: = D DIV B;
D: = D mod b;
END;
While (LEN> 1) and (c [len] = 0) THEN DEC (LEN);
C [0]: = LEN;
END;
6. High precision divide high precision
Procedure high_devide (A, B: HP; VAR C, D: HP);
VAR
I, LEN: Integer;
Begin
Fillchar (C, SizeOf (C), 0);
Fillchar (D, SizeOf (D), 0);
Len: = a [0]; d [0]: = 1;
For i: = len downto 1 do begin
Multiply (d, 10, d);
D [1]: = a [i];
While (COMPARE (D, B)> = 0) DO {D> = B}
Begin
Subtract (d, b, d);
INC (C [I]);
END;
END;
While (LEN> 1) AND (C.S [LEN] = 0) DO DEC (LEN);
C.1: = LEN;
END;