1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//! Exponentiation.

use crate::{
    ibig::IBig,
    primitive::PrimitiveUnsigned,
    sign::Sign::*,
    ubig::{Repr::*, UBig},
};

impl UBig {
    /// Raises self to the power of `exp`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ibig::ubig;
    /// assert_eq!(ubig!(3).pow(3), ubig!(27));
    /// ```
    pub fn pow(&self, exp: usize) -> UBig {
        match exp {
            0 => return UBig::from_word(1),
            1 => return self.clone(),
            2 => return self * self,
            _ => {}
        }
        match self.repr() {
            Small(0) => return UBig::from_word(0),
            Small(1) => return UBig::from_word(1),
            Small(2) => {
                let mut x = UBig::from_word(0);
                x.set_bit(exp);
                return x;
            }
            _ => {}
        }
        let mut p = usize::BIT_SIZE - 2 - exp.leading_zeros();
        let mut res = self * self;
        loop {
            if exp & (1 << p) != 0 {
                res *= self;
            }
            if p == 0 {
                break;
            }
            p -= 1;
            res = &res * &res;
        }
        res
    }
}

impl IBig {
    /// Raises self to the power of `exp`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ibig::ibig;
    /// assert_eq!(ibig!(-3).pow(3), ibig!(-27));
    /// ```
    pub fn pow(&self, exp: usize) -> IBig {
        let sign = if self.sign() == Negative && exp % 2 == 1 {
            Negative
        } else {
            Positive
        };
        IBig::from_sign_magnitude(sign, self.magnitude().pow(exp))
    }
}