最近研究二维码时发现有的地方需要进行多项式除法,于是自己写了一个算法,以活动一下脑子。
//初始化数组,赋值0.
procedure InitArray(var bb : array of double);
var
a : integer;
begin
for a := 0 to high(bb) do
begin
bb[a] := 0;
end;
end;
//多项式计算.
procedure CountMultiExpress(var dXiShu1,dXiShu2,dXiShu3,dXiShu4 : array of double;AMaxMiCi:integer);
var
//多项式表达规则:认为输入的都是标准的表达式f(x)=a0*x^0+a1*x^1+a2*x^2+...+an*x^n
//系数从0-20存a0-a20,幂为对应的数组索引
//dXiShu1为分母,dXishu2为分子, 3为商 4为余数。
//这里的计算仅仅支持常数系数的。
dXiShuTmp : array of double;
dTmp1,dTmp2,dMaxMiCi,dMaxXiShu : double;
i,j,iTmpMiCi,iMaxMiCi:integer;
procedure InitArray(var bb : array of double);
var
a : integer;
begin
for a := 0 to high(bb) do
begin
bb[a] := 0;
end;
end;
begin
Setlength(dXiShuTmp,AMaxMiCi);
//获取多项式分子最大幂次和系数。
for i:= 20 downto 0 do
begin
if dXiShu2[i]<>0.0 then
begin
dMaxMiCi := i;
dMaxXiShu := dXiShu2[i];
break;
end;
end;
//计算,从高到低
iMaxMiCi := trunc(dMaxMiCi);
for i:= AMaxMiCi downto iMaxMiCi do
begin
if dXiShu1[i]<> 0.0 then
begin
dTmp1 := dXiShu1[i] / dMaxXiShu;
iTmpMiCi := i - iMaxMiCi;
dXiShu3[iTmpMiCi] := dTmp1;//商.
InitArray(dXiShuTmp);
//分子乘dTmp1
for j := iMaxMiCi downto 0 do
begin
dXishuTmp[j+iTmpMiCi] := dXiShu2[j] * dTmp1;
end;
//做减法分母-dXishuTmp
for j := i downto 0 do
begin
dXishu1[j] := dXishu1[j]-dXishuTmp[j];
end;
end;
end;
//余数
for j := 0 to AMaxMiCi do
begin
dXiShu4[j] := dXiShu1[j];
end;
Setlength(dXiShuTmp,0);
end;
使用:
procedure TForm1.Button5Click(Sender: TObject);
var
dXiShu1,dXiShu2,dXiShu3,dXiShu4 : array[0..20] of double;
strOut1,strOut2:string;
j : integer;
begin
//初始化
InitArray(dXiShu1);
InitArray(dXiShu2);
InitArray(dXiShu3);
InitArray(dXiShu4);
//分母,分子赋值
dXiShu1[0]:= 7;
dXiShu1[1]:= 4;
dXiShu1[2]:= 6;
dXiShu1[3]:= 0;
dXiShu1[4]:= 0;
dXiShu1[5]:= 0;
dXiShu2[0]:= 3;
dXiShu2[1]:= 2;
dXiShu2[2]:= 0;
dXiShu2[3]:= 0;
dXiShu2[4]:= 0;
dXiShu2[5]:= 0;
CountMultiExpress(dXiShu1,dXiShu2,dXiShu3,dXiShu4,20);
//输出结果
strOut1 := '';
strOut2 := '';
for j := 0 to 20 do
begin
//商
if dXiShu3[j] > 0.0 then
begin
strOut2 := ' +'+floattostr(dXiShu3[j])+'x^'+inttostr(j)+' ' + strOut2 ;
end;
if dXiShu3[j] < 0.0 then
begin
strOut2 := ' '+floattostr(dXiShu3[j])+'x^'+inttostr(j)+' ' + strOut2 ;
end;
//余数
if dXiShu4[j] > 0.0 then
begin
strOut1 := ' +'+floattostr(dXiShu4[j])+'x^'+inttostr(j)+' ' + strOut1 ;
end;
if dXiShu4[j] < 0.0 then
begin
strOut1 := ' '+floattostr(dXiShu4[j])+'x^'+inttostr(j)+' ' + strOut1 ;
end;
end;
strOut1 := trim(strOut1);
strOut2 := trim(strOut2);
if strOut1[1]='+' then
strOut1 := copy(strOut1,2,length(strOut1)-1);
if strOut2[1]='+' then
strOut2 := copy(strOut2,2,length(strOut2)-1);
memo3.Lines.Clear();
memo3.Lines.Append('商数:'+ strOut2);
memo3.Lines.Append('余数:'+ strOut1);
end;