LargeInteger, being descended from Number does actually have a pow function.
pow for LargeInteger
-
01-10-2022 - |
Pergunta
LargeInteger
doesn't seem to have a pow
function, or if it does, it cannot process pow(0)
though BigInteger
can.
I have tried to construct my own, but memory seems to spike badly, and there may be an infinite loop as it runs endlessly:
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;
}
}
How can a pow
method be developed for LargeInteger
?
Solução 2
Outras dicas
Each time through your for
loop, you are effectively squaring the result with this line:
base = base.times(base);
You would wind up with base
to the power of (2 to the exponent
power), not base
to the power of exponent
.
Start with 1
and multiply in the base
each loop.
LargeInteger result = LargeInteger.valueOf(1);
for(int i = 0; i < exponent; i++){
result = result.times(base);
}
return result;
For optimization, you can try modifying the algorithm to use exponentiation-by-squaring.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow