我有一个我用ADA编写的Karatsuba算法实现。
procedure Karatsuba (Factor_1, Factor_2 : in Number; Product : out Number) is
m : Integer;
m2 : Integer;
low1 : Number := (0,1);
high1 : Number := (0,1);
low2 : Number := (0,1);
high2 : Number := (0,1);
z0 : Index;
z1 : Index;
z2 : Index;
x : Integer;
y : Integer;
hc1 : Index;
hc2 : Index;
begin
low1 := (others => 0);
high1 := (others => 0);
low2 := (others => 0);
high2 := (others => 0);
if Factor_1'Length = 1 or Factor_2'Length = 1 then
Standard(Factor_1, Factor_2,Product);
end if;
-- calculates the size of the numbers
m := Integer'Max(Factor_1'Length, Factor_2'Length);
m2 := m / 2;
-- split the digit sequences about the middle
for Factor_1_Index in Factor_1'Range loop
x := x + 1;
if x <= m2 then
low1(Factor_1_Index) := Factor_1(Factor_1_Index);
else
high1(hc1) := Factor_1(Factor_1_Index);
hc1 := hc1 + 1;
end if;
end loop;
for Factor_2_Index in Factor_2'Range loop
y := y + 1;
if y <= m2 then
low2(Factor_2_Index) := Factor_2(Factor_2_Index);
else
high2(hc2) := Factor_2(Factor_2_Index);
hc2 := hc2 + 1;
end if;
end loop;
-- 3 calls made to numbers approximately half the size
z0 := Karatsuba(low1, low2, Product);
z1 := Karatsuba((low1 + high1), (low2 + high2), Product);
z2 := Karatsuba(high1, high2, Product);
Product := (z2*10**(2*m2))+((z1-z2-z0)*10**(m2))+(z0);
end Karatsuba;
在“结束Karatsuba”行之前的最后4行,我得到错误“期望类型'索引'定义为......”。我收到的错误分别是
expected type "Index" defined at ....
found package or procedure name
there is no applicable operator "+" for type "Number" defined at ......
这是我分配了一些变量的另一个类:
package ITI8590.Natural_Number_Multiplication is
type Digit is range 0 .. 1;
type Index is new Positive;
type Number is array (Index range <>) of Digit;
for Digit'Size use 1;
procedure Standard(Factor_1, Factor_2 : in Number; Product : out Number);
procedure Karatsuba(Factor_1, Factor_2 : in Number; Product : out Number);
end ITI8590.Natural_Number_Multiplication;
为什么我会收到此错误?我无法解决它,我陷入其中。你能帮帮我吗?
谢谢,
答案 0 :(得分:3)
Karatsuba
是一个程序,所以最后而不是
z0 := Karatsuba(low1, low2, Product);
z1 := Karatsuba((low1 + high1), (low2 + high2), Product);
z2 := Karatsuba(high1, high2, Product);
应该阅读
Karatsuba(low1, low2, z0);
Karatsuba((low1 + high1), (low2 + high2), z1);
Karatsuba(high1, high2, z2);
要求您将z0
,z1
,z2
声明为Number
而不是Index
。请注意,Product
是过程的out
参数,因此您获得的所有代码都是使用中间结果覆盖两次(3次,计算上面对Standard
的调用)。
但是你遇到了问题:编译器说
yusuf.ada:25:12: unconstrained subtype not allowed (need initialization)
yusuf.ada:25:12: provide initial value or explicit array bounds
正在调用与您声明low1
等方式相关的内容:
low1 : Number := (0,1);
high1 : Number := (0,1);
low2 : Number := (0,1);
high2 : Number := (0,1);
这种方法的问题在于您现在已经约束了变量的边界:low1
被修复为具有2个元素(设置为您随后覆盖的值),并且无法展开。我不知道该算法应该如何工作,但这似乎不太合适;首先,如果输入超过2位,会发生什么?
可能有效的一种方法是使用输入参数中的位数:
Max_Digits : constant Positive := Factor_1’Length + Factor_2’length;
pragma Assert (Product’Length >= Max_Digits, “possible overflow”);
low1 : Number (1 .. Max_Digits) := (others => 0);
等
而且,正如ajb所评论的那样,您需要在+
s和{{之间定义运算符-
,*
,**
,Number
1}}根据需要,特别是在过程的最后一行中的表达式Integers
中。