malachite_base/num/arithmetic/saturating_pow.rs
1// Copyright © 2025 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::num::arithmetic::traits::{Parity, SaturatingPow, SaturatingPowAssign};
10use crate::num::basic::signeds::PrimitiveSigned;
11use crate::num::basic::unsigneds::PrimitiveUnsigned;
12
13fn saturating_pow_unsigned<T: PrimitiveUnsigned>(x: T, exp: u64) -> T {
14 if exp == 0 {
15 T::ONE
16 } else if x < T::TWO {
17 x
18 } else if let Some(p) = x.checked_pow(exp) {
19 p
20 } else {
21 T::MAX
22 }
23}
24
25fn saturating_pow_signed<T: PrimitiveSigned>(x: T, exp: u64) -> T {
26 if exp == 0 {
27 T::ONE
28 } else if x == T::ZERO || x == T::ONE {
29 x
30 } else if x == T::NEGATIVE_ONE {
31 if exp.even() { T::ONE } else { T::NEGATIVE_ONE }
32 } else if let Some(p) = x.checked_pow(exp) {
33 p
34 } else if x > T::ZERO || exp.even() {
35 T::MAX
36 } else {
37 T::MIN
38 }
39}
40
41macro_rules! impl_saturating_pow_unsigned {
42 ($t:ident) => {
43 impl SaturatingPow<u64> for $t {
44 type Output = $t;
45
46 /// This is a wrapper over the `saturating_pow` functions in the standard library, for
47 /// example [this one](u32::saturating_pow).
48 #[inline]
49 fn saturating_pow(self, exp: u64) -> $t {
50 saturating_pow_unsigned(self, exp)
51 }
52 }
53 };
54}
55apply_to_unsigneds!(impl_saturating_pow_unsigned);
56
57macro_rules! impl_saturating_pow_signed {
58 ($t:ident) => {
59 impl SaturatingPow<u64> for $t {
60 type Output = $t;
61
62 /// This is a wrapper over the `saturating_pow` functions in the standard library, for
63 /// example [this one](i32::saturating_pow).
64 #[inline]
65 fn saturating_pow(self, exp: u64) -> $t {
66 saturating_pow_signed(self, exp)
67 }
68 }
69 };
70}
71apply_to_signeds!(impl_saturating_pow_signed);
72
73macro_rules! impl_saturating_pow_primitive_int {
74 ($t:ident) => {
75 impl SaturatingPowAssign<u64> for $t {
76 /// Raises a number to a power, in place, saturating at the numeric bounds instead of
77 /// overflowing.
78 ///
79 /// $$
80 /// x \gets \\begin{cases}
81 /// x^y & \text{if} \\quad m \leq x^y \leq M, \\\\
82 /// M & \text{if} \\quad x^y > M, \\\\
83 /// m & \text{if} \\quad x^y < m,
84 /// \\end{cases}
85 /// $$
86 /// where $m$ is `Self::MIN` and $M$ is `Self::MAX`.
87 ///
88 /// # Worst-case complexity
89 /// Constant time and additional memory.
90 ///
91 /// # Examples
92 /// See [here](super::saturating_pow#saturating_pow_assign).
93 #[inline]
94 fn saturating_pow_assign(&mut self, exp: u64) {
95 *self = SaturatingPow::saturating_pow(*self, exp);
96 }
97 }
98 };
99}
100apply_to_primitive_ints!(impl_saturating_pow_primitive_int);