Search code examples
rustrust-cargo

How can I calculate power of two BigInts/BigUints?


The title says it all. I tried to find something in the Rust docs but the only thing I came across is this function for the BigInt/Biguint structs.

pub fn modpow(&self, exponent: &Self, modulus: &Self) -> Self

I also found this function in the num::pow but it doesn't help me as my exp is BigInt/BigUint too.

pub fn pow<T>(base: T, exp: usize) -> T

So, anyone has any idea? I'm thinking that I should use the modpow function somehow, but what do I send for the modulus parameter?


Solution

  • You can convert the exponent to usize and then call BigUint::pow(). If the exponent is larger than usize::MAX, you won't be able to calculate the power anyway. For example:

    use num_bigint::BigUint;
    use std::convert::TryInto;
    
    fn pow(n: BigUint, exp: BigUint) -> BigUint {
        n.pow(exp.try_into().expect("exponent too large for pow()"))
    }
    

    Playground