Ada中的任意长度整数 [英] Arbitrary length integer in Ada
问题描述
我目前正在自学Ada,尽管我可以从解决一些较常规的问题开始入手。
I am currently teaching myself Ada and though I could begin by tackling some of the more conventional problems to get started.
更具体地说,我尝试计算阶乘n !,而n> 100。到目前为止,我的实现是:
More specifically I try to calculate the factorial n!, whereas n>100. My implementation so far is:
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>引发CONTRAINT_ERROR异常20。
The problem is obviously that even Long_Long_Integer is may too small for this and throws a CONTRAINT_ERROR exception for n>20.
是否有一个实现任意大小整数的包?
Is there a package that implements arbitrary-sized integers?
谢谢!
PS:我确实选择不使用递归,因为我想探索此练习中的循环。但是,否则请对代码的所有方面(样式,最佳实践,错误..)进行评论。
PS: I did opt against recursion because I wanted to explore loops in this exercise. But otherwise please comment on all aspects of the code (style, best-practices, error..)
推荐答案
Ada加密库支持无符号大数字( Big_Numbers
)。您可以从 http://sourceforge.net/projects/libadacrypt-dev/下载
库。
我建议您检查svn。当前版本的Big_Numbers乘法函数
有一个小错误。
The Ada Crypto Library supports big unsigned numbers (Big_Numbers
). You can download
the lib from http://sourceforge.net/projects/libadacrypt-dev/.
I recommend checking out the svn. The Big_Numbers multiplication function
of the current release has a minor bug.
您可以使用当前的GNAT编译器从 AdaCore Libre网站。
You can compile the lib with the current GNAT compiler from the AdaCore Libre site.
lib无法在gcc下编译-4.3或gcc-4.4,因为 gcc中的错误。
The lib will not compile under gcc-4.3 or gcc-4.4 because of a bug in gcc.
最后,我将举一个小例子,说明如何将LibAdaCrypt中的两个512位Big_Numbers
相乘。
Finally, I will give you a small exmple how to multiply two 512-bit Big_Numbers from the LibAdaCrypt.
package Test.Big_Numbers is
with Crypto.Types.Big_Numbers;
pragma Elaborate_All(Crypto.Types.Big_Numbers);
package Big is new Crypto.Types.Big_Numbers(512);
use Big;
use Big.Utils;
end Test.Big_Numbers;
package body Test.Big_Numbers is
x : Big_Unsigned := To_Big_Unsigned("16#57C19F8F7866F8633AC1D25B92FC83B4#");
Y : Big_Unsigned := To_Big_Unsigned("16#FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF60#");
x := X * Y;
Put_Line(X);
end Test.Big_Numbers;
Best regards
Christian
这篇关于Ada中的任意长度整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!