pow函数适用于大整数。

3

LargeInteger没有pow函数,如果有的话,它无法处理pow(0),而BigInteger可以。

我试着自己构建了一个,但内存占用似乎很高,而且可能会有无限循环,因为它一直在运行:

public static LargeInteger liPow(LargeInteger base, int exponent){
    if(exponent == 0){
        return LargeInteger.valueOf(1);
    }
    else if(exponent == 1){
        return base;
    }
    else{
        for(int i=1; i<exponent; i++){
            base = base.times(base);
        }
        return base;
    }
}

如何为LargeInteger开发一个pow方法?


2
你实际上并不是在计算 pow(),而是一些更大的函数 base^(2^exp) - Sirko
@Mysticial 谢谢你,Mysticial!我一定会去研究一下的! - user1382306
1
糟糕,我刚回复完你就不小心删除了我的评论。这是我再次发出的建议:使用这个算法:http://en.wikipedia.org/wiki/Exponentiation_by_squaring。 - Mysticial
@Mysticial - 我认为他/她正在尝试。 - Dawood ibn Kareem
@DavidWallace 这是pscience的库。如果它像广告中所说的那样好,也许用Java签名ed25519就不需要一整秒钟了!;)) - user1382306
@DavidWallace 这就是我一开始删除它的原因。我认为 OP 试图顺序相乘。 - Mysticial
2个回答

4

每次通过你的for循环,这一行代码实际上是将结果平方:

base = base.times(base);

你会得到 base 的 (2 的 exponent 次方) 次幂,而不是 baseexponent 次幂。
1 开始,并在每次循环中乘以 base
LargeInteger result = LargeInteger.valueOf(1);
for(int i = 0; i < exponent; i++){
    result = result.times(base);
}
return result;

为了优化,您可以尝试修改算法使用平方法求幂


谢谢您,rgettman!我会在确保pow仅对<= 0抱怨后尝试使用它。 - user1382306

2

LargeInteger是从Number继承而来的,因此它实际上具有一个pow函数。


谢谢Quirlom!我注意到它在参数不是0时不会报错。所以我应该检查那个而不是0吗?非常感谢您的帮助! - user1382306
source来看,如果指数<=0,则它们会抛出异常,因此我会检查指数是否为0并返回1。 - Sinkingpoint
再次感谢Quirlon!下次我会更深入地查找类“链”以寻找答案,现在我知道了如果我至少不知道它叫什么。;)) - user1382306

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接