我目前正在自学 Ada,虽然我可以从解决一些更传统的问题开始。
更具体地说,我尝试计算阶乘 n!,而 n>100。到目前为止,我的实现是:
with Ada.Text_IO;
with Ada.Integer_Text_IO;
use Ada.Text_IO;
procedure Factorial is
-- define a type covering the range beginning at 1 up to which faculty is to
-- be computed.
subtype Argument is Long_Long_Integer range 1..100;
-- define a type that is large enough to hold the result
subtype Result is Long_Long_Integer range 1..Long_Long_Integer'Last;
package Result_IO is new Ada.Text_IO.Integer_IO(Result); use Result_IO;
-- variable holding the faculty calculated.
fac : Result := 1;
begin
-- loop over whole range of ARGUMENT and calculate n!
for n in ARGUMENT loop
fac := (fac * n);
end loop;
end;
问题显然是即使 Long_Long_Integer 也可能太小,并且对于 n>20 会引发 CONTRAINT_ERROR 异常。
是否有实现任意大小整数的包?
谢谢!
PS:我确实选择了反对递归,因为我想在这个练习中探索循环。但除此之外,请评论代码的所有方面(样式、最佳实践、错误..)