[][src]Trait num_integer::Roots

pub trait Roots: Integer {
    fn nth_root(&self, n: u32) -> Self;

    fn sqrt(&self) -> Self { ... }
fn cbrt(&self) -> Self { ... } }

Provides methods to compute an integer's square root, cube root, and arbitrary nth root.

Required methods

fn nth_root(&self, n: u32) -> Self

Returns the truncated principal nth 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:

println!("can't compute ⁰√x : {}", 123.nth_root(0));

or if n is even and self is negative:

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);
Loading content...

Provided methods

fn sqrt(&self) -> 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:

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);

fn cbrt(&self) -> Self

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));
Loading content...

Implementations on Foreign Types

impl Roots for i8[src]

impl Roots for i16[src]

impl Roots for i32[src]

impl Roots for i64[src]

impl Roots for i128[src]

impl Roots for isize[src]

impl Roots for u8[src]

impl Roots for u16[src]

impl Roots for u32[src]

impl Roots for u64[src]

impl Roots for u128[src]

impl Roots for usize[src]

Loading content...

Implementors

Loading content...