num_integer/roots.rs
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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
use core;
use core::mem;
use traits::checked_pow;
use traits::PrimInt;
use Integer;
/// Provides methods to compute an integer's square root, cube root,
/// and arbitrary `n`th root.
pub trait Roots: Integer {
/// Returns the truncated principal `n`th root of an integer
/// -- `if x >= 0 { ⌊ⁿ√x⌋ } else { ⌈ⁿ√x⌉ }`
///
/// This is solving for `r` in `rⁿ = x`, rounding toward zero.
/// If `x` is positive, the result will satisfy `rⁿ ≤ x < (r+1)ⁿ`.
/// If `x` is negative and `n` is odd, then `(r-1)ⁿ < x ≤ rⁿ`.
///
/// # Panics
///
/// Panics if `n` is zero:
///
/// ```should_panic
/// # use num_integer::Roots;
/// println!("can't compute ⁰√x : {}", 123.nth_root(0));
/// ```
///
/// or if `n` is even and `self` is negative:
///
/// ```should_panic
/// # use num_integer::Roots;
/// println!("no imaginary numbers... {}", (-1).nth_root(10));
/// ```
///
/// # Examples
///
/// ```
/// use num_integer::Roots;
///
/// let x: i32 = 12345;
/// assert_eq!(x.nth_root(1), x);
/// assert_eq!(x.nth_root(2), x.sqrt());
/// assert_eq!(x.nth_root(3), x.cbrt());
/// assert_eq!(x.nth_root(4), 10);
/// assert_eq!(x.nth_root(13), 2);
/// assert_eq!(x.nth_root(14), 1);
/// assert_eq!(x.nth_root(std::u32::MAX), 1);
///
/// assert_eq!(std::i32::MAX.nth_root(30), 2);
/// assert_eq!(std::i32::MAX.nth_root(31), 1);
/// assert_eq!(std::i32::MIN.nth_root(31), -2);
/// assert_eq!((std::i32::MIN + 1).nth_root(31), -1);
///
/// assert_eq!(std::u32::MAX.nth_root(31), 2);
/// assert_eq!(std::u32::MAX.nth_root(32), 1);
/// ```
fn nth_root(&self, n: u32) -> Self;
/// Returns the truncated principal square root of an integer -- `⌊√x⌋`
///
/// This is solving for `r` in `r² = x`, rounding toward zero.
/// The result will satisfy `r² ≤ x < (r+1)²`.
///
/// # Panics
///
/// Panics if `self` is less than zero:
///
/// ```should_panic
/// # use num_integer::Roots;
/// println!("no imaginary numbers... {}", (-1).sqrt());
/// ```
///
/// # Examples
///
/// ```
/// use num_integer::Roots;
///
/// let x: i32 = 12345;
/// assert_eq!((x * x).sqrt(), x);
/// assert_eq!((x * x + 1).sqrt(), x);
/// assert_eq!((x * x - 1).sqrt(), x - 1);
/// ```
#[inline]
fn sqrt(&self) -> Self {
self.nth_root(2)
}
/// Returns the truncated principal cube root of an integer --
/// `if x >= 0 { ⌊∛x⌋ } else { ⌈∛x⌉ }`
///
/// This is solving for `r` in `r³ = x`, rounding toward zero.
/// If `x` is positive, the result will satisfy `r³ ≤ x < (r+1)³`.
/// If `x` is negative, then `(r-1)³ < x ≤ r³`.
///
/// # Examples
///
/// ```
/// use num_integer::Roots;
///
/// let x: i32 = 1234;
/// assert_eq!((x * x * x).cbrt(), x);
/// assert_eq!((x * x * x + 1).cbrt(), x);
/// assert_eq!((x * x * x - 1).cbrt(), x - 1);
///
/// assert_eq!((-(x * x * x)).cbrt(), -x);
/// assert_eq!((-(x * x * x + 1)).cbrt(), -x);
/// assert_eq!((-(x * x * x - 1)).cbrt(), -(x - 1));
/// ```
#[inline]
fn cbrt(&self) -> Self {
self.nth_root(3)
}
}
/// Returns the truncated principal square root of an integer --
/// see [Roots::sqrt](trait.Roots.html#method.sqrt).
#[inline]
pub fn sqrt<T: Roots>(x: T) -> T {
x.sqrt()
}
/// Returns the truncated principal cube root of an integer --
/// see [Roots::cbrt](trait.Roots.html#method.cbrt).
#[inline]
pub fn cbrt<T: Roots>(x: T) -> T {
x.cbrt()
}
/// Returns the truncated principal `n`th root of an integer --
/// see [Roots::nth_root](trait.Roots.html#tymethod.nth_root).
#[inline]
pub fn nth_root<T: Roots>(x: T, n: u32) -> T {
x.nth_root(n)
}
macro_rules! signed_roots {
($T:ty, $U:ty) => {
impl Roots for $T {
#[inline]
fn nth_root(&self, n: u32) -> Self {
if *self >= 0 {
(*self as $U).nth_root(n) as Self
} else {
assert!(n.is_odd(), "even roots of a negative are imaginary");
-((self.wrapping_neg() as $U).nth_root(n) as Self)
}
}
#[inline]
fn sqrt(&self) -> Self {
assert!(*self >= 0, "the square root of a negative is imaginary");
(*self as $U).sqrt() as Self
}
#[inline]
fn cbrt(&self) -> Self {
if *self >= 0 {
(*self as $U).cbrt() as Self
} else {
-((self.wrapping_neg() as $U).cbrt() as Self)
}
}
}
};
}
signed_roots!(i8, u8);
signed_roots!(i16, u16);
signed_roots!(i32, u32);
signed_roots!(i64, u64);
#[cfg(has_i128)]
signed_roots!(i128, u128);
signed_roots!(isize, usize);
#[inline]
fn fixpoint<T, F>(mut x: T, f: F) -> T
where
T: Integer + Copy,
F: Fn(T) -> T,
{
let mut xn = f(x);
while x < xn {
x = xn;
xn = f(x);
}
while x > xn {
x = xn;
xn = f(x);
}
x
}
#[inline]
fn bits<T>() -> u32 {
8 * mem::size_of::<T>() as u32
}
#[inline]
fn log2<T: PrimInt>(x: T) -> u32 {
debug_assert!(x > T::zero());
bits::<T>() - 1 - x.leading_zeros()
}
macro_rules! unsigned_roots {
($T:ident) => {
impl Roots for $T {
#[inline]
fn nth_root(&self, n: u32) -> Self {
fn go(a: $T, n: u32) -> $T {
// Specialize small roots
match n {
0 => panic!("can't find a root of degree 0!"),
1 => return a,
2 => return a.sqrt(),
3 => return a.cbrt(),
_ => (),
}
// The root of values less than 2ⁿ can only be 0 or 1.
if bits::<$T>() <= n || a < (1 << n) {
return (a > 0) as $T;
}
if bits::<$T>() > 64 {
// 128-bit division is slow, so do a bitwise `nth_root` until it's small enough.
return if a <= core::u64::MAX as $T {
(a as u64).nth_root(n) as $T
} else {
let lo = (a >> n).nth_root(n) << 1;
let hi = lo + 1;
// 128-bit `checked_mul` also involves division, but we can't always
// compute `hiⁿ` without risking overflow. Try to avoid it though...
if hi.next_power_of_two().trailing_zeros() * n >= bits::<$T>() {
match checked_pow(hi, n as usize) {
Some(x) if x <= a => hi,
_ => lo,
}
} else {
if hi.pow(n) <= a {
hi
} else {
lo
}
}
};
}
#[cfg(feature = "std")]
#[inline]
fn guess(x: $T, n: u32) -> $T {
// for smaller inputs, `f64` doesn't justify its cost.
if bits::<$T>() <= 32 || x <= core::u32::MAX as $T {
1 << ((log2(x) + n - 1) / n)
} else {
((x as f64).ln() / f64::from(n)).exp() as $T
}
}
#[cfg(not(feature = "std"))]
#[inline]
fn guess(x: $T, n: u32) -> $T {
1 << ((log2(x) + n - 1) / n)
}
// https://en.wikipedia.org/wiki/Nth_root_algorithm
let n1 = n - 1;
let next = |x: $T| {
let y = match checked_pow(x, n1 as usize) {
Some(ax) => a / ax,
None => 0,
};
(y + x * n1 as $T) / n as $T
};
fixpoint(guess(a, n), next)
}
go(*self, n)
}
#[inline]
fn sqrt(&self) -> Self {
fn go(a: $T) -> $T {
if bits::<$T>() > 64 {
// 128-bit division is slow, so do a bitwise `sqrt` until it's small enough.
return if a <= core::u64::MAX as $T {
(a as u64).sqrt() as $T
} else {
let lo = (a >> 2u32).sqrt() << 1;
let hi = lo + 1;
if hi * hi <= a {
hi
} else {
lo
}
};
}
if a < 4 {
return (a > 0) as $T;
}
#[cfg(feature = "std")]
#[inline]
fn guess(x: $T) -> $T {
(x as f64).sqrt() as $T
}
#[cfg(not(feature = "std"))]
#[inline]
fn guess(x: $T) -> $T {
1 << ((log2(x) + 1) / 2)
}
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
let next = |x: $T| (a / x + x) >> 1;
fixpoint(guess(a), next)
}
go(*self)
}
#[inline]
fn cbrt(&self) -> Self {
fn go(a: $T) -> $T {
if bits::<$T>() > 64 {
// 128-bit division is slow, so do a bitwise `cbrt` until it's small enough.
return if a <= core::u64::MAX as $T {
(a as u64).cbrt() as $T
} else {
let lo = (a >> 3u32).cbrt() << 1;
let hi = lo + 1;
if hi * hi * hi <= a {
hi
} else {
lo
}
};
}
if bits::<$T>() <= 32 {
// Implementation based on Hacker's Delight `icbrt2`
let mut x = a;
let mut y2 = 0;
let mut y = 0;
let smax = bits::<$T>() / 3;
for s in (0..smax + 1).rev() {
let s = s * 3;
y2 *= 4;
y *= 2;
let b = 3 * (y2 + y) + 1;
if x >> s >= b {
x -= b << s;
y2 += 2 * y + 1;
y += 1;
}
}
return y;
}
if a < 8 {
return (a > 0) as $T;
}
if a <= core::u32::MAX as $T {
return (a as u32).cbrt() as $T;
}
#[cfg(feature = "std")]
#[inline]
fn guess(x: $T) -> $T {
(x as f64).cbrt() as $T
}
#[cfg(not(feature = "std"))]
#[inline]
fn guess(x: $T) -> $T {
1 << ((log2(x) + 2) / 3)
}
// https://en.wikipedia.org/wiki/Cube_root#Numerical_methods
let next = |x: $T| (a / (x * x) + x * 2) / 3;
fixpoint(guess(a), next)
}
go(*self)
}
}
};
}
unsigned_roots!(u8);
unsigned_roots!(u16);
unsigned_roots!(u32);
unsigned_roots!(u64);
#[cfg(has_i128)]
unsigned_roots!(u128);
unsigned_roots!(usize);