求助一道pascal高精度乘法题:输入两个正整数m、n,输出他们的积.( 1
来源:学生作业帮助网 编辑:作业帮 时间:2024/11/08 07:54:19
求助一道pascal高精度乘法题:输入两个正整数m、n,输出他们的积.( 1
求助一道pascal高精度乘法题:输入两个正整数m、n,输出他们的积.( 1
求助一道pascal高精度乘法题:输入两个正整数m、n,输出他们的积.( 1
高精度与高精度乘法
【问题描述】
设高精度数a[1]a[2]...a[n-1]a[n]与高精度b[1]b[2]...b[n-1]b[n]的乘法可表示如下:
a,b:array[1..n] of 0..9;即:
a[1]a[2]...a[n-1]a[n]
* b[1]b[2]...b[n-1]b[n]
-----------------------------
c[1]c[2]...c[2n-1]c[2n]
【算法分析】
从低位开始乘:
1.首先计算
a[1] a[2]... a[n-1] a[n]
* b[n]
---------------------------------
d[0]d[1] d[2]...d[n-1] d[n]
得到中间结果,然后将d数组加到C数组中.
2.再计算
a[1] a[2]... a[n-1] a[n]
* b[n-1]
---------------------------------
d[0]d[1] d[2]... d[n-1] d[n]
然后再错位相加:
c[1]...c[n-1] c[n] c[n+1] ... c[2n-1] c[2n]
+ d[0] d[1] d[2] ... d[n]
----------------------------------------------
c[1]...c[n-1] c[n] c[n+1] ... c[2n-1] c[2n]
3.一般算法:
c[1]c[2]...c[2n-1]c[2n]清零:
for i:=1 to 2*n do c[i]:=0;
for i:=n downto 1 do
begin g:=0;
for j:=n downto 1 do
begin s:=a[j]*b[i]+g; d[j]:=s mod 10; g:=s div 10 end;
d[0]:=g;
g:=0;
for j:=n downto 0 do
begin s:=d[j]+c[i+j]+g; c[i+j]:=s mod 10; g:=s div 10 end;
end;
【样例输入】
123456789
100000000
【样例输出】
12345678900000000
【参考程序】
program aa;
const n=100;
type arrtype=array[0..n] of integer;
arrtype2=array[1..2*n] of integer;
var a,b,d:arrtype; c:arrtype2; g:integer;
procedure readdata(var int:arrtype);
var ch:char; i,k:integer;
begin read(ch); k:=0;
whiLe ch in['0'..'9'] do
begin inc(k); int[k]:=ord(ch)-48; read(ch); end;
for i:=k downto 1 do begin int[n+i-k]:=int[i]; int[i]:=0; end;
end;
procedure workout;
var i,j,s:integer;
begin
for i:=n downto 1 do
begin g:=0;
for j:=n downto 1 do
begin s:=a[j]*b[i]+g; d[j]:=s mod 10; g:=s div 10; end;
d[0]:=s; g:=0;
for j:=n downto 0 do
begin s:=d[j]+c[i+j]+g; c[i+j]:=s mod 10; g:=s div 10 end;
end;
end;
procedure outdata(a:arrtype2);
var j:integer;
begin j:=1;
whiLe (a[j]=0) and (j