openssl包使用相应的方法实现bignum类,以进行算术和比较,以对任意大小的整数执行计算。

在密码学中,modular exponent x^p %% m有一个常见的特殊情况,例如rsa。对于较大的p,计算x^p是不可行的,但是可以有效地计算x^p %% m OpenSSL在BN_mod_exp()中实现的^.bignum

R是否提供任何机制来实现%%.bignumx^y %% z方法,以便在评估x^p时可以调用此特殊情况,而不是实际计算?

最佳答案

聚会晚了,但是是的,这是绝对可能的,并且在某些语言(例如C ++)中这是一种中等通用的编程技术,该技术称为expression templates

弱类型的R无法完全利用模式。但是“轻”版本仍然是可能的。

简而言之,您可以定义^.bignum运算符,以便代替或立即计算结果,它返回一个表示“幂运算”的代理对象。此代理对象有一个特别覆盖的%%方法,该方法调用ExpMod实现(例如BM_mod_exp)。它还定义了一种方法,可以通过评估实际的bignum操作将其强制为x ^ y

在代码中,可能如下所示:

# Vectorisation left as an exercise for the reader.

`^.bignum` = function (x, y)
    structure(c(x, y), class = 'bignum_mod_exp_proxy')

eval_exp = function (x)
    call_actual_exp(x[1], x[2])

as.bignum = function (x)
    if (inherits(x, 'bignum_mod_exp_proxy'))
        eval_exp(x)
    else
        # … implement other coercions to bignum, e.g. from `numeric`.

`%%.bignum_mod_exp_proxy` = function (x, y)
    call_BN_mod_exp(x[1], x[2], y)

# Pretend that a `bignum_mod_exp_proxy` in all other contexts. E.g.:

print.bignum_mod_exp_proxy = function (x, ...)
    print(eval_exp(x))

# … etc., for the rest of the `bignum` operations.


实际上,您甚至可以覆盖=.bignum_mod_exp_proxy<-.bignum_mod_exp_proxyassign.bignum_mod_exp_proxy(将assign转换为S3泛型),以便将赋值z = x ^ y评估为bignum。但是,这可能是多余的,并且会给每个作业带来额外的开销。

关于r - R中的优化算术方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33725811/

10-12 17:36