Struct SmallInteger

Source
pub struct SmallInteger { /* private fields */ }
๐Ÿ‘ŽDeprecated since 1.23.0: use MiniInteger instead
Expand description

A small integer that did not require any memory allocation until version 1.23.0.

Because of a soundness issue, this has been deprecated and replaced by MiniInteger. To fix the soundness issue, this struct now uses allocations like Integer itself, so it is less efficient than MiniInteger.

The SmallInteger type can be coerced to an Integer, as it implements Deref<Target = Integer>.

ยงExamples

#![allow(deprecated)]

use rug::integer::SmallInteger;
use rug::Integer;
// `a` requires a heap allocation
let mut a = Integer::from(250);
// `b` can reside on the stack
let b = SmallInteger::from(-100);
a.lcm_mut(&b);
assert_eq!(a, 500);
// another computation:
a.lcm_mut(&SmallInteger::from(30));
assert_eq!(a, 1500);

Implementationsยง

Sourceยง

impl SmallInteger

Source

pub const fn new() -> Self

Creates a SmallInteger with value 0.

ยงExamples
#![allow(deprecated)]

use rug::integer::SmallInteger;
let i = SmallInteger::new();
// Borrow i as if it were Integer.
assert_eq!(*i, 0);
Source

pub unsafe fn as_nonreallocating_integer(&mut self) -> &mut Integer

Returns a mutable reference to an Integer for simple operations that do not need to allocate more space for the number.

ยงSafety

It is undefined behavior to perform operations that reallocate the internal data of the referenced Integer or to swap it with another number.

Some GMP functions swap the allocations of their target operands; calling such functions with the mutable reference returned by this method can lead to undefined behavior.

ยงExamples
#![allow(deprecated)]

use rug::integer::SmallInteger;
use rug::Assign;
let mut i = SmallInteger::from(1u64);
let capacity = i.capacity();
// another u64 will not require a reallocation
unsafe {
    i.as_nonreallocating_integer().assign(2u64);
}
assert_eq!(*i, 2);
assert_eq!(i.capacity(), capacity);

Methods from Deref<Target = Integer>ยง

Source

pub const ZERO: Integer

Source

pub const ONE: &'static Integer

Source

pub const NEG_ONE: &'static Integer

Source

pub fn capacity(&self) -> usize

Returns the capacity in bits that can be stored without reallocating.

ยงExamples
use rug::Integer;
let i = Integer::with_capacity(137);
assert!(i.capacity() >= 137);
Source

pub fn as_raw(&self) -> *const mpz_t

Returns a pointer to the inner GMP integer.

The returned pointer will be valid for as long as self is valid.

ยงExamples
use gmp_mpfr_sys::gmp;
use rug::Integer;
let i = Integer::from(15);
let z_ptr = i.as_raw();
unsafe {
    let u = gmp::mpz_get_ui(z_ptr);
    assert_eq!(u, 15);
}
// i is still valid
assert_eq!(i, 15);
Source

pub fn significant_digits<T: UnsignedPrimitive>(&self) -> usize

Returns the number of digits of type T required to represent the absolute value.

T can be any unsigned integer primitive type.

ยงExamples
use rug::Integer;

let i: Integer = Integer::from(1) << 256;
assert_eq!(i.significant_digits::<bool>(), 257);
assert_eq!(i.significant_digits::<u8>(), 33);
assert_eq!(i.significant_digits::<u16>(), 17);
assert_eq!(i.significant_digits::<u32>(), 9);
assert_eq!(i.significant_digits::<u64>(), 5);
Source

pub fn to_digits<T: UnsignedPrimitive>(&self, order: Order) -> Vec<T>

Converts the absolute value to a Vec of digits of type T, where T can be any unsigned integer primitive type.

The Integer type also has the as_limbs method, which can be used to borrow the digits without copying them. This does come with some more constraints compared to to_digits:

  1. The digit width is not optional and depends on the implementation: limb_t is typically u64 on 64-bit systems and u32 on 32-bit systems.
  2. The order is not optional and is least significant digit first, with each digit in the targetโ€™s endianness, equivalent to Order::Lsf.
ยงExamples
use rug::integer::Order;
use rug::Integer;
let i = Integer::from(0x1234_5678_9abc_def0u64);
let digits = i.to_digits::<u32>(Order::MsfBe);
assert_eq!(digits, [0x1234_5678u32.to_be(), 0x9abc_def0u32.to_be()]);

let zero = Integer::new();
let digits_zero = zero.to_digits::<u32>(Order::MsfBe);
assert!(digits_zero.is_empty());
Source

pub fn write_digits<T: UnsignedPrimitive>(&self, digits: &mut [T], order: Order)

Writes the absolute value into a slice of digits of type T, where T can be any unsigned integer primitive type.

The slice must be large enough to hold the digits; the minimum size can be obtained using the significant_digits method.

ยงPanics

Panics if the slice does not have sufficient capacity.

ยงExamples
use rug::integer::Order;
use rug::Integer;
let i = Integer::from(0x1234_5678_9abc_def0u64);
let mut digits = [0xffff_ffffu32; 4];
i.write_digits(&mut digits, Order::MsfBe);
let word0 = 0x9abc_def0u32;
let word1 = 0x1234_5678u32;
assert_eq!(digits, [0, 0, word1.to_be(), word0.to_be()]);
Source

pub unsafe fn write_digits_unaligned<T: UnsignedPrimitive>( &self, dst: *mut T, len: usize, order: Order, )

Writes the absolute value into a memory area of digits of type T, where T can be any unsigned integer primitive type.

The memory area is addressed using a pointer and a length. The len parameter is the number of digits, not the number of bytes.

The length must be large enough to hold the digits; the minimum length can be obtained using the significant_digits method.

There are no data alignment restrictions on dst, any address is allowed.

The memory locations can be uninitialized before this method is called; this method sets all len elements, padding with zeros if the length is larger than required.

ยงSafety

To avoid undefined behavior, dst must be valid for writing len digits, that is len ร— size_of::<T>() bytes.

ยงPanics

Panics if the length is less than the number of digits.

ยงExamples
use rug::integer::Order;
use rug::Integer;
let i = Integer::from(0xfedc_ba98_7654_3210u64);
let mut digits = [0xffff_ffffu32; 4];
let ptr = digits.as_mut_ptr();
unsafe {
    let unaligned = (ptr.cast::<u8>()).offset(2).cast::<u32>();
    i.write_digits_unaligned(unaligned, 3, Order::MsfBe);
}
assert_eq!(
    digits,
    [
        0xffff_0000u32.to_be(),
        0x0000_fedcu32.to_be(),
        0xba98_7654u32.to_be(),
        0x3210_ffffu32.to_be(),
    ]
);

The following example shows how to write into uninitialized memory. In practice, the following code could be replaced by a call to the safe method to_digits.

use rug::integer::Order;
use rug::Integer;
let i = Integer::from(0x1234_5678_9abc_def0u64);
let len = i.significant_digits::<u32>();
assert_eq!(len, 2);

// The following code is equivalent to:
//     let digits = i.to_digits::<u32>(Order::MsfBe);
let mut digits = Vec::<u32>::with_capacity(len);
let ptr = digits.as_mut_ptr();
unsafe {
    i.write_digits_unaligned(ptr, len, Order::MsfBe);
    digits.set_len(len);
}

assert_eq!(digits, [0x1234_5678u32.to_be(), 0x9abc_def0u32.to_be()]);
Source

pub fn as_limbs(&self) -> &[limb_t] โ“˜

Extracts a slice of limbs used to store the value.

The slice contains the absolute value of self, with the least significant limb first.

The Integer type also implements AsRef<[limb_t]>, which is equivalent to this method.

ยงExamples
use rug::Integer;
assert!(Integer::new().as_limbs().is_empty());
assert_eq!(Integer::from(13).as_limbs(), &[13]);
assert_eq!(Integer::from(-23).as_limbs(), &[23]);

int.as_limbs() is like a borrowing non-copy version of int.to_digits::<[limb_t]>(Order::Lsf).

use gmp_mpfr_sys::gmp::limb_t;
use rug::integer::Order;
use rug::Integer;
let int = Integer::from(0x1234_5678_9abc_def0u64);
// no copying for int_slice, which is borrowing int
let int_slice = int.as_limbs();
// digits is a copy and does not borrow int
let digits = int.to_digits::<limb_t>(Order::Lsf);
// no copying for digits_slice, which is borrowing digits
let digits_slice = &digits[..];
assert_eq!(int_slice, digits_slice);
Source

pub fn to_i8(&self) -> Option<i8>

Converts to an i8 if the value fits.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let fits = Integer::from(-100);
assert_eq!(fits.to_i8(), Some(-100));
let small = Integer::from(-200);
assert_eq!(small.to_i8(), None);
let large = Integer::from(200);
assert_eq!(large.to_i8(), None);
Source

pub fn to_i16(&self) -> Option<i16>

Converts to an i16 if the value fits.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let fits = Integer::from(-30_000);
assert_eq!(fits.to_i16(), Some(-30_000));
let small = Integer::from(-40_000);
assert_eq!(small.to_i16(), None);
let large = Integer::from(40_000);
assert_eq!(large.to_i16(), None);
Source

pub fn to_i32(&self) -> Option<i32>

Converts to an i32 if the value fits.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let fits = Integer::from(-50);
assert_eq!(fits.to_i32(), Some(-50));
let small = Integer::from(-123456789012345_i64);
assert_eq!(small.to_i32(), None);
let large = Integer::from(123456789012345_i64);
assert_eq!(large.to_i32(), None);
Source

pub fn to_i64(&self) -> Option<i64>

Converts to an i64 if the value fits.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let fits = Integer::from(-50);
assert_eq!(fits.to_i64(), Some(-50));
let small = Integer::from_str_radix("-fedcba9876543210", 16).unwrap();
assert_eq!(small.to_i64(), None);
let large = Integer::from_str_radix("fedcba9876543210", 16).unwrap();
assert_eq!(large.to_i64(), None);
Source

pub fn to_i128(&self) -> Option<i128>

Converts to an i128 if the value fits.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let fits = Integer::from(-50);
assert_eq!(fits.to_i128(), Some(-50));
let small: Integer = Integer::from(-1) << 130;
assert_eq!(small.to_i128(), None);
let large: Integer = Integer::from(1) << 130;
assert_eq!(large.to_i128(), None);
Source

pub fn to_isize(&self) -> Option<isize>

Converts to an isize if the value fits.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let fits = Integer::from(0x1000);
assert_eq!(fits.to_isize(), Some(0x1000));
let large: Integer = Integer::from(0x1000) << 128;
assert_eq!(large.to_isize(), None);
Source

pub fn to_u8(&self) -> Option<u8>

Converts to an u8 if the value fits.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let fits = Integer::from(200);
assert_eq!(fits.to_u8(), Some(200));
let neg = Integer::from(-1);
assert_eq!(neg.to_u8(), None);
let large = Integer::from(300);
assert_eq!(large.to_u8(), None);
Source

pub fn to_u16(&self) -> Option<u16>

Converts to an u16 if the value fits.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let fits = Integer::from(60_000);
assert_eq!(fits.to_u16(), Some(60_000));
let neg = Integer::from(-1);
assert_eq!(neg.to_u16(), None);
let large = Integer::from(70_000);
assert_eq!(large.to_u16(), None);
Source

pub fn to_u32(&self) -> Option<u32>

Converts to an u32 if the value fits.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let fits = Integer::from(1234567890);
assert_eq!(fits.to_u32(), Some(1234567890));
let neg = Integer::from(-1);
assert_eq!(neg.to_u32(), None);
let large = Integer::from(123456789012345_u64);
assert_eq!(large.to_u32(), None);
Source

pub fn to_u64(&self) -> Option<u64>

Converts to an u64 if the value fits.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let fits = Integer::from(123456789012345_u64);
assert_eq!(fits.to_u64(), Some(123456789012345));
let neg = Integer::from(-1);
assert_eq!(neg.to_u64(), None);
let large = "1234567890123456789012345".parse::<Integer>().unwrap();
assert_eq!(large.to_u64(), None);
Source

pub fn to_u128(&self) -> Option<u128>

Converts to an u128 if the value fits.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let fits = Integer::from(12345678901234567890_u128);
assert_eq!(fits.to_u128(), Some(12345678901234567890));
let neg = Integer::from(-1);
assert_eq!(neg.to_u128(), None);
let large = "1234567890123456789012345678901234567890"
    .parse::<Integer>()
    .unwrap();
assert_eq!(large.to_u128(), None);
Source

pub fn to_usize(&self) -> Option<usize>

Converts to an usize if the value fits.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let fits = Integer::from(0x1000);
assert_eq!(fits.to_usize(), Some(0x1000));
let neg = Integer::from(-1);
assert_eq!(neg.to_usize(), None);
let large: Integer = Integer::from(0x1000) << 128;
assert_eq!(large.to_usize(), None);
Source

pub fn to_i8_wrapping(&self) -> i8

Converts to an i8, wrapping if the value does not fit.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let large = Integer::from(0x1234);
assert_eq!(large.to_i8_wrapping(), 0x34);
Source

pub fn to_i16_wrapping(&self) -> i16

Converts to an i16, wrapping if the value does not fit.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let large = Integer::from(0x1234_5678);
assert_eq!(large.to_i16_wrapping(), 0x5678);
Source

pub fn to_i32_wrapping(&self) -> i32

Converts to an i32, wrapping if the value does not fit.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let large = Integer::from(0x1234_5678_9abc_def0_u64);
assert_eq!(large.to_i32_wrapping(), 0x9abc_def0_u32 as i32);
Source

pub fn to_i64_wrapping(&self) -> i64

Converts to an i64, wrapping if the value does not fit.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let large = Integer::from_str_radix("f123456789abcdef0", 16).unwrap();
assert_eq!(large.to_i64_wrapping(), 0x1234_5678_9abc_def0);
Source

pub fn to_i128_wrapping(&self) -> i128

Converts to an i128, wrapping if the value does not fit.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let s = "f123456789abcdef0123456789abcdef0";
let large = Integer::from_str_radix(s, 16).unwrap();
assert_eq!(
    large.to_i128_wrapping(),
    0x1234_5678_9abc_def0_1234_5678_9abc_def0
);
Source

pub fn to_isize_wrapping(&self) -> isize

Converts to an isize, wrapping if the value does not fit.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let large: Integer = (Integer::from(0x1000) << 128) | 0x1234;
assert_eq!(large.to_isize_wrapping(), 0x1234);
Source

pub fn to_u8_wrapping(&self) -> u8

Converts to a u8, wrapping if the value does not fit.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let neg = Integer::from(-1);
assert_eq!(neg.to_u8_wrapping(), 0xff);
let large = Integer::from(0x1234);
assert_eq!(large.to_u8_wrapping(), 0x34);
Source

pub fn to_u16_wrapping(&self) -> u16

Converts to a u16, wrapping if the value does not fit.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let neg = Integer::from(-1);
assert_eq!(neg.to_u16_wrapping(), 0xffff);
let large = Integer::from(0x1234_5678);
assert_eq!(large.to_u16_wrapping(), 0x5678);
Source

pub fn to_u32_wrapping(&self) -> u32

Converts to a u32, wrapping if the value does not fit.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let neg = Integer::from(-1);
assert_eq!(neg.to_u32_wrapping(), 0xffff_ffff);
let large = Integer::from(0x1234_5678_9abc_def0_u64);
assert_eq!(large.to_u32_wrapping(), 0x9abc_def0);
Source

pub fn to_u64_wrapping(&self) -> u64

Converts to a u64, wrapping if the value does not fit.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let neg = Integer::from(-1);
assert_eq!(neg.to_u64_wrapping(), 0xffff_ffff_ffff_ffff);
let large = Integer::from_str_radix("f123456789abcdef0", 16).unwrap();
assert_eq!(large.to_u64_wrapping(), 0x1234_5678_9abc_def0);
Source

pub fn to_u128_wrapping(&self) -> u128

Converts to a u128, wrapping if the value does not fit.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let neg = Integer::from(-1);
assert_eq!(
    neg.to_u128_wrapping(),
    0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff
);
let s = "f123456789abcdef0123456789abcdef0";
let large = Integer::from_str_radix(s, 16).unwrap();
assert_eq!(
    large.to_u128_wrapping(),
    0x1234_5678_9abc_def0_1234_5678_9abc_def0
);
Source

pub fn to_usize_wrapping(&self) -> usize

Converts to a usize, wrapping if the value does not fit.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let large: Integer = (Integer::from(0x1000) << 128) | 0x1234;
assert_eq!(large.to_usize_wrapping(), 0x1234);
Source

pub fn to_f32(&self) -> f32

Converts to an f32, rounding towards zero.

This conversion can also be performed using

ยงExamples
use rug::Integer;
let min = Integer::from_f32(f32::MIN).unwrap();
let min_minus_one = min - 1u32;
// min_minus_one is truncated to f32::MIN
assert_eq!(min_minus_one.to_f32(), f32::MIN);
let times_two = min_minus_one * 2u32;
// times_two is too small
assert_eq!(times_two.to_f32(), f32::NEG_INFINITY);
Source

pub fn to_f64(&self) -> f64

Converts to an f64, rounding towards zero.

This conversion can also be performed using

ยงExamples
use rug::Integer;

// An `f64` has 53 bits of precision.
let exact = 0x1f_ffff_ffff_ffff_u64;
let i = Integer::from(exact);
assert_eq!(i.to_f64(), exact as f64);

// large has 56 ones
let large = 0xff_ffff_ffff_ffff_u64;
// trunc has 53 ones followed by 3 zeros
let trunc = 0xff_ffff_ffff_fff8_u64;
let j = Integer::from(large);
assert_eq!(j.to_f64() as u64, trunc);

let max = Integer::from_f64(f64::MAX).unwrap();
let max_plus_one = max + 1u32;
// max_plus_one is truncated to f64::MAX
assert_eq!(max_plus_one.to_f64(), f64::MAX);
let times_two = max_plus_one * 2u32;
// times_two is too large
assert_eq!(times_two.to_f64(), f64::INFINITY);
Source

pub fn to_f32_exp(&self) -> (f32, u32)

Converts to an f32 and an exponent, rounding towards zero.

The returned f32 is in the range 0.5ย โ‰คย xย <ย 1. If the value is zero, (0.0, 0) is returned.

ยงExamples
use rug::Integer;
let zero = Integer::new();
let (d0, exp0) = zero.to_f32_exp();
assert_eq!((d0, exp0), (0.0, 0));
let fifteen = Integer::from(15);
let (d15, exp15) = fifteen.to_f32_exp();
assert_eq!((d15, exp15), (15.0 / 16.0, 4));
Source

pub fn to_f64_exp(&self) -> (f64, u32)

Converts to an f64 and an exponent, rounding towards zero.

The returned f64 is in the range 0.5ย โ‰คย xย <ย 1. If the value is zero, (0.0, 0) is returned.

ยงExamples
use rug::Integer;
let zero = Integer::new();
let (d0, exp0) = zero.to_f64_exp();
assert_eq!((d0, exp0), (0.0, 0));
let fifteen = Integer::from(15);
let (d15, exp15) = fifteen.to_f64_exp();
assert_eq!((d15, exp15), (15.0 / 16.0, 4));
Source

pub fn to_string_radix(&self, radix: i32) -> String

Returns a string representation of the number for the specified radix.

ยงPanics

Panics if radix is less than 2 or greater than 36.

ยงExamples
use rug::{Assign, Integer};
let mut i = Integer::new();
assert_eq!(i.to_string_radix(10), "0");
i.assign(-10);
assert_eq!(i.to_string_radix(16), "-a");
i.assign(0x1234cdef);
assert_eq!(i.to_string_radix(4), "102031030313233");
i.assign(Integer::parse_radix("123456789aAbBcCdDeEfF", 16).unwrap());
assert_eq!(i.to_string_radix(16), "123456789aabbccddeeff");
Source

pub fn as_neg(&self) -> BorrowInteger<'_>

Borrows a negated copy of the Integer.

The returned object implements Deref<Target = Integer>.

This method performs a shallow copy and negates it, and negation does not change the allocated data.

ยงExamples
use rug::Integer;
let i = Integer::from(42);
let neg_i = i.as_neg();
assert_eq!(*neg_i, -42);
// methods taking &self can be used on the returned object
let reneg_i = neg_i.as_neg();
assert_eq!(*reneg_i, 42);
assert_eq!(*reneg_i, i);
Source

pub fn as_abs(&self) -> BorrowInteger<'_>

Borrows an absolute copy of the Integer.

The returned object implements Deref<Target = Integer>.

This method performs a shallow copy and possibly negates it, and negation does not change the allocated data.

ยงExamples
use rug::Integer;
let i = Integer::from(-42);
let abs_i = i.as_abs();
assert_eq!(*abs_i, 42);
// methods taking &self can be used on the returned object
let reabs_i = abs_i.as_abs();
assert_eq!(*reabs_i, 42);
assert_eq!(*reabs_i, *abs_i);
Source

pub fn as_rational(&self) -> BorrowRational<'_>

Borrows a copy of the Integer as a Rational number.

The returned object implements Deref<Target = Rational>.

ยงExamples
use rug::Integer;
let i = Integer::from(4);
let r = i.as_rational();
assert_eq!(*r, 4);
// methods taking &self can be used on the returned object
let recip_r = r.as_recip();
assert_eq!(*recip_r, 0.25);
Source

pub fn is_zero(&self) -> bool

Returns true if the number is zero.

ยงExamples
use rug::Integer;
assert!(Integer::from(0).is_zero());
assert!(!(Integer::from(1).is_zero()));
Source

pub fn is_positive(&self) -> bool

Returns true if the number is positive and false if the number is zero or negative.

ยงExamples
use rug::Integer;
assert!(Integer::from(10).is_positive());
assert!(!(Integer::from(-10).is_positive()));
Source

pub fn is_negative(&self) -> bool

Returns true if the number is negative and false if the number is zero or positive.

ยงExamples
use rug::Integer;
assert!(Integer::from(-10).is_negative());
assert!(!(Integer::from(10).is_negative()));
Source

pub fn is_even(&self) -> bool

Returns true if the number is even.

ยงExamples
use rug::Integer;
assert!(!(Integer::from(13).is_even()));
assert!(Integer::from(-14).is_even());
Source

pub fn is_odd(&self) -> bool

Returns true if the number is odd.

ยงExamples
use rug::Integer;
assert!(Integer::from(13).is_odd());
assert!(!Integer::from(-14).is_odd());
Source

pub fn is_divisible(&self, divisor: &Self) -> bool

Returns true if the number is divisible by divisor. Unlike other division functions, divisor can be zero.

ยงExamples
use rug::Integer;
let i = Integer::from(230);
assert!(i.is_divisible(&Integer::from(10)));
assert!(!i.is_divisible(&Integer::from(100)));
assert!(!i.is_divisible(&Integer::new()));
Source

pub fn is_divisible_u(&self, divisor: u32) -> bool

Returns true if the number is divisible by divisor. Unlike other division functions, divisor can be zero.

ยงExamples
use rug::Integer;
let i = Integer::from(230);
assert!(i.is_divisible_u(23));
assert!(!i.is_divisible_u(100));
assert!(!i.is_divisible_u(0));
Source

pub fn is_divisible_2pow(&self, b: u32) -> bool

Returns true if the number is divisible by 2b.

ยงExamples
use rug::Integer;
let i = Integer::from(15 << 17);
assert!(i.is_divisible_2pow(16));
assert!(i.is_divisible_2pow(17));
assert!(!i.is_divisible_2pow(18));
Source

pub fn is_congruent(&self, c: &Self, divisor: &Self) -> bool

Returns true if the number is congruent to c mod divisor, that is, if there exists a q such that self = c + q ร— divisor. Unlike other division functions, divisor can be zero.

ยงExamples
use rug::Integer;
let n = Integer::from(105);
let divisor = Integer::from(10);
assert!(n.is_congruent(&Integer::from(5), &divisor));
assert!(n.is_congruent(&Integer::from(25), &divisor));
assert!(!n.is_congruent(&Integer::from(7), &divisor));
// n is congruent to itself if divisor is 0
assert!(n.is_congruent(&n, &Integer::from(0)));
Source

pub fn is_congruent_u(&self, c: u32, divisor: u32) -> bool

Returns true if the number is congruent to c mod divisor, that is, if there exists a q such that self = c + q ร— divisor. Unlike other division functions, divisor can be zero.

ยงExamples
use rug::Integer;
let n = Integer::from(105);
assert!(n.is_congruent_u(3335, 10));
assert!(!n.is_congruent_u(107, 10));
// n is congruent to itself if divisor is 0
assert!(n.is_congruent_u(105, 0));
Source

pub fn is_congruent_2pow(&self, c: &Self, b: u32) -> bool

Returns true if the number is congruent to c mod 2b, that is, if there exists a q such that self = c + q ร— 2b.

ยงExamples
use rug::Integer;
let n = Integer::from(13 << 17 | 21);
assert!(n.is_congruent_2pow(&Integer::from(7 << 17 | 21), 17));
assert!(!n.is_congruent_2pow(&Integer::from(13 << 17 | 22), 17));
Source

pub fn is_perfect_power(&self) -> bool

Returns true if the number is a perfect power.

ยงExamples
use rug::Integer;
// 0 is 0 to the power of anything
assert!(Integer::from(0).is_perfect_power());
// 25 is 5 to the power of 2
assert!(Integer::from(25).is_perfect_power());
// -243 is -3 to the power of 5
assert!(Integer::from(243).is_perfect_power());

assert!(!Integer::from(24).is_perfect_power());
assert!(!Integer::from(-100).is_perfect_power());
Source

pub fn is_perfect_square(&self) -> bool

Returns true if the number is a perfect square.

ยงExamples
use rug::Integer;
assert!(Integer::from(0).is_perfect_square());
assert!(Integer::from(1).is_perfect_square());
assert!(Integer::from(4).is_perfect_square());
assert!(Integer::from(9).is_perfect_square());

assert!(!Integer::from(15).is_perfect_square());
assert!(!Integer::from(-9).is_perfect_square());
Source

pub fn is_power_of_two(&self) -> bool

Returns true if the number is a power of two.

ยงExamples
use rug::Integer;
assert!(Integer::from(1).is_power_of_two());
assert!(Integer::from(4).is_power_of_two());
assert!(Integer::from(1 << 30).is_power_of_two());

assert!(!Integer::from(7).is_power_of_two());
assert!(!Integer::from(0).is_power_of_two());
assert!(!Integer::from(-1).is_power_of_two());
Source

pub fn cmp0(&self) -> Ordering

Returns the same result as self.cmp(&0.into()), but is faster.

ยงExamples
use core::cmp::Ordering;
use rug::Integer;
assert_eq!(Integer::from(-5).cmp0(), Ordering::Less);
assert_eq!(Integer::from(0).cmp0(), Ordering::Equal);
assert_eq!(Integer::from(5).cmp0(), Ordering::Greater);
Source

pub fn cmp_abs(&self, other: &Self) -> Ordering

Compares the absolute values.

ยงExamples
use core::cmp::Ordering;
use rug::Integer;
let a = Integer::from(-10);
let b = Integer::from(4);
assert_eq!(a.cmp(&b), Ordering::Less);
assert_eq!(a.cmp_abs(&b), Ordering::Greater);
Source

pub fn significant_bits(&self) -> u32

Returns the number of bits required to represent the absolute value.

ยงExamples
use rug::Integer;

assert_eq!(Integer::from(0).significant_bits(), 0);  //    โ€œโ€
assert_eq!(Integer::from(1).significant_bits(), 1);  //   โ€œ1โ€
assert_eq!(Integer::from(4).significant_bits(), 3);  // โ€œ100โ€
assert_eq!(Integer::from(7).significant_bits(), 3);  // โ€œ111โ€
assert_eq!(Integer::from(-1).significant_bits(), 1); //   โ€œ1โ€
assert_eq!(Integer::from(-4).significant_bits(), 3); // โ€œ100โ€
assert_eq!(Integer::from(-7).significant_bits(), 3); // โ€œ111โ€
Source

pub fn signed_bits(&self) -> u32

Returns the number of bits required to represent the value using a twoโ€™s-complement representation.

For non-negative numbers, this method returns one more than the significant_bits method, since an extra zero is needed before the most significant bit.

ยงExamples
use rug::Integer;

assert_eq!(Integer::from(-5).signed_bits(), 4); // โ€œ1011โ€
assert_eq!(Integer::from(-4).signed_bits(), 3); //  โ€œ100โ€
assert_eq!(Integer::from(-3).signed_bits(), 3); //  โ€œ101โ€
assert_eq!(Integer::from(-2).signed_bits(), 2); //   โ€œ10โ€
assert_eq!(Integer::from(-1).signed_bits(), 1); //    โ€œ1โ€
assert_eq!(Integer::from(0).signed_bits(), 1);  //    โ€œ0โ€
assert_eq!(Integer::from(1).signed_bits(), 2);  //   โ€œ01โ€
assert_eq!(Integer::from(2).signed_bits(), 3);  //  โ€œ010โ€
assert_eq!(Integer::from(3).signed_bits(), 3);  //  โ€œ011โ€
assert_eq!(Integer::from(4).signed_bits(), 4);  // โ€œ0100โ€
Source

pub fn count_ones(&self) -> Option<u32>

Returns the number of one bits if the value โ‰ฅ 0.

ยงExamples
use rug::Integer;
assert_eq!(Integer::from(0).count_ones(), Some(0));
assert_eq!(Integer::from(15).count_ones(), Some(4));
assert_eq!(Integer::from(-1).count_ones(), None);
Source

pub fn count_zeros(&self) -> Option<u32>

Returns the number of zero bits if the value < 0.

ยงExamples
use rug::Integer;
assert_eq!(Integer::from(0).count_zeros(), None);
assert_eq!(Integer::from(1).count_zeros(), None);
assert_eq!(Integer::from(-1).count_zeros(), Some(0));
assert_eq!(Integer::from(-2).count_zeros(), Some(1));
assert_eq!(Integer::from(-7).count_zeros(), Some(2));
assert_eq!(Integer::from(-8).count_zeros(), Some(3));
Source

pub fn find_zero(&self, start: u32) -> Option<u32>

Returns the location of the first zero, starting at start. If the bit at location start is zero, returns start.

ยงExamples
use rug::Integer;
// -2 is ...11111110
assert_eq!(Integer::from(-2).find_zero(0), Some(0));
assert_eq!(Integer::from(-2).find_zero(1), None);
// 15 is ...00001111
assert_eq!(Integer::from(15).find_zero(0), Some(4));
assert_eq!(Integer::from(15).find_zero(20), Some(20));
Source

pub fn find_one(&self, start: u32) -> Option<u32>

Returns the location of the first one, starting at start. If the bit at location start is one, returns start.

ยงExamples
use rug::Integer;
// 1 is ...00000001
assert_eq!(Integer::from(1).find_one(0), Some(0));
assert_eq!(Integer::from(1).find_one(1), None);
// -16 is ...11110000
assert_eq!(Integer::from(-16).find_one(0), Some(4));
assert_eq!(Integer::from(-16).find_one(20), Some(20));
Source

pub fn get_bit(&self, index: u32) -> bool

Returns true if the bit at location index is 1 or false if the bit is 0.

ยงExamples
use rug::Integer;
let i = Integer::from(0b100101);
assert!(i.get_bit(0));
assert!(!i.get_bit(1));
assert!(i.get_bit(5));
let neg = Integer::from(-1);
assert!(neg.get_bit(1000));
Source

pub fn hamming_dist(&self, other: &Self) -> Option<u32>

Retuns the Hamming distance if the two numbers have the same sign.

The Hamming distance is the number of different bits.

ยงExamples
use rug::Integer;
let i = Integer::from(-1);
assert_eq!(Integer::from(0).hamming_dist(&i), None);
assert_eq!(Integer::from(-1).hamming_dist(&i), Some(0));
// -1 is ...11111111 and -13 is ...11110011
assert_eq!(Integer::from(-13).hamming_dist(&i), Some(2));
Source

pub fn abs_ref(&self) -> AbsIncomplete<'_>

Computes the absolute value.

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::Integer;
let i = Integer::from(-100);
let r = i.abs_ref();
let abs = Integer::from(r);
assert_eq!(abs, 100);
assert_eq!(i, -100);
Source

pub fn signum_ref(&self) -> SignumIncomplete<'_>

Computes the signum.

  • 0 if the value is zero
  • 1 if the value is positive
  • โˆ’1 if the value is negative

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::Integer;
let i = Integer::from(-100);
let r = i.signum_ref();
let signum = Integer::from(r);
assert_eq!(signum, -1);
assert_eq!(i, -100);
Source

pub fn clamp_ref<'min, 'max, Min, Max>( &self, min: &'min Min, max: &'max Max, ) -> ClampIncomplete<'_, 'min, 'max, Min, Max>
where Self: PartialOrd<Min> + PartialOrd<Max> + for<'a> Assign<&'a Min> + for<'a> Assign<&'a Max>,

Clamps the value within the specified bounds.

The following are implemented with the returned incomplete-computation value as Src:

ยงPanics

Panics if the maximum value is less than the minimum value.

ยงExamples
use rug::Integer;
let min = -10;
let max = 10;
let too_small = Integer::from(-100);
let r1 = too_small.clamp_ref(&min, &max);
let clamped1 = Integer::from(r1);
assert_eq!(clamped1, -10);
let in_range = Integer::from(3);
let r2 = in_range.clamp_ref(&min, &max);
let clamped2 = Integer::from(r2);
assert_eq!(clamped2, 3);
Source

pub fn keep_bits_ref(&self, n: u32) -> KeepBitsIncomplete<'_>

Keeps the n least significant bits only, producing a result that is greater or equal to 0.

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::Integer;
let i = Integer::from(-1);
let r = i.keep_bits_ref(8);
let eight_bits = Integer::from(r);
assert_eq!(eight_bits, 0xff);
Source

pub fn keep_signed_bits_ref(&self, n: u32) -> KeepSignedBitsIncomplete<'_>

Keeps the n least significant bits only, producing a negative result if the nth least significant bit is one.

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::Integer;
let i = Integer::from(-1);
let r = i.keep_signed_bits_ref(8);
let eight_bits = Integer::from(r);
assert_eq!(eight_bits, -1);
Source

pub fn next_power_of_two_ref(&self) -> NextPowerOfTwoIncomplete<'_>

Finds the next power of two, or 1 if the number โ‰ค 0.

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::Integer;
let i = Integer::from(53);
let r = i.next_power_of_two_ref();
let next = Integer::from(r);
assert_eq!(next, 64);
Source

pub fn modulo_ref<'a>(&'a self, divisor: &'a Self) -> ModuloIncomplete<'a>

Finds the modulus, or the remainder of Euclidean division.

The result is always zero or positive.

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::Integer;
let dividend = Integer::from(-1003);
let divisor = Integer::from(-10);
let r = dividend.modulo_ref(&divisor);
let modulus = Integer::from(r);
assert_eq!(modulus, 7);
Source

pub fn div_rem_ref<'a>(&'a self, divisor: &'a Self) -> DivRemIncomplete<'a>

Performs a division producing both the quotient and remainder.

The following are implemented with the returned incomplete-computation value as Src:

The remainder has the same sign as the dividend.

ยงExamples
use rug::{Complete, Integer};
let dividend = Integer::from(-23);
let divisor = Integer::from(-10);
let (quotient, rem) = dividend.div_rem_ref(&divisor).complete();
assert_eq!(quotient, 2);
assert_eq!(rem, -3);
Source

pub fn div_rem_ceil_ref<'a>( &'a self, divisor: &'a Self, ) -> DivRemCeilIncomplete<'a>

Performs a division producing both the quotient and remainder, with the quotient rounded up.

The sign of the remainder is the opposite of the divisorโ€™s sign.

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::{Complete, Integer};
let dividend = Integer::from(-23);
let divisor = Integer::from(-10);
let (quotient, rem) = dividend.div_rem_ceil_ref(&divisor).complete();
assert_eq!(quotient, 3);
assert_eq!(rem, 7);
Source

pub fn div_rem_floor_ref<'a>( &'a self, divisor: &'a Self, ) -> DivRemFloorIncomplete<'a>

Performs a division producing both the quotient and remainder, with the quotient rounded down.

The remainder has the same sign as the divisor.

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::{Complete, Integer};
let dividend = Integer::from(-23);
let divisor = Integer::from(-10);
let (quotient, rem) = dividend.div_rem_floor_ref(&divisor).complete();
assert_eq!(quotient, 2);
assert_eq!(rem, -3);
Source

pub fn div_rem_round_ref<'a>( &'a self, divisor: &'a Self, ) -> DivRemRoundIncomplete<'a>

Performs a division producing both the quotient and remainder, with the quotient rounded to the nearest integer.

When the quotient before rounding lies exactly between two integers, it is rounded away from zero.

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::{Complete, Integer};
// -28 / -10 โ†’ 3 rem 2
let dividend = Integer::from(-28);
let divisor = Integer::from(-10);
let (quotient, rem) = dividend.div_rem_round_ref(&divisor).complete();
assert_eq!(quotient, 3);
assert_eq!(rem, 2);
Source

pub fn div_rem_euc_ref<'a>( &'a self, divisor: &'a Self, ) -> DivRemEucIncomplete<'a>

Performs Euclidan division producing both the quotient and remainder, with a positive remainder.

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::{Complete, Integer};
let dividend = Integer::from(-23);
let divisor = Integer::from(-10);
let (quotient, rem) = dividend.div_rem_euc_ref(&divisor).complete();
assert_eq!(quotient, 3);
assert_eq!(rem, 7);
Source

pub fn mod_u(&self, modulo: u32) -> u32

Returns the modulo, or the remainder of Euclidean division by a u32.

The result is always zero or positive.

ยงPanics

Panics if modulo is zero.

ยงExamples
use rug::Integer;
let pos = Integer::from(23);
assert_eq!(pos.mod_u(1), 0);
assert_eq!(pos.mod_u(10), 3);
assert_eq!(pos.mod_u(100), 23);
let neg = Integer::from(-23);
assert_eq!(neg.mod_u(1), 0);
assert_eq!(neg.mod_u(10), 7);
assert_eq!(neg.mod_u(100), 77);
Source

pub fn div_exact_ref<'a>(&'a self, divisor: &'a Self) -> DivExactIncomplete<'a>

Performs an exact division.

This is much faster than normal division, but produces correct results only when the division is exact.

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::Integer;
let i = Integer::from(12345 * 54321);
let divisor = Integer::from(12345);
let r = i.div_exact_ref(&divisor);
let quotient = Integer::from(r);
assert_eq!(quotient, 54321);
Source

pub fn div_exact_u_ref(&self, divisor: u32) -> DivExactUIncomplete<'_>

Performs an exact division.

This is much faster than normal division, but produces correct results only when the division is exact.

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::Integer;
let i = Integer::from(12345 * 54321);
let r = i.div_exact_u_ref(12345);
assert_eq!(Integer::from(r), 54321);
Source

pub fn invert_ref<'a>( &'a self, modulo: &'a Self, ) -> Option<InvertIncomplete<'a>>

Finds the inverse modulo modulo if an inverse exists.

The inverse exists if the modulo is not zero, and self and the modulo are co-prime, that is their GCD is 1.

The following are implemented with the unwrapped returned incomplete-computation value as Src:

ยงExamples
use rug::Integer;
let two = Integer::from(2);
let four = Integer::from(4);
let five = Integer::from(5);

// Modulo 4, 2 has no inverse, there is no i such that 2 ร— i = 1.
// For this conversion, if no inverse exists, the Integer
// created is left unchanged as 0.
assert!(two.invert_ref(&four).is_none());

// Modulo 5, the inverse of 2 is 3, as 2 ร— 3 = 1.
let r = two.invert_ref(&five).unwrap();
let inverse = Integer::from(r);
assert_eq!(inverse, 3);
Source

pub fn pow_mod_ref<'a>( &'a self, exponent: &'a Self, modulo: &'a Self, ) -> Option<PowModIncomplete<'a>>

Raises a number to the power of exponent modulo modulo if an answer exists.

If the exponent is negative, then the number must have an inverse for an answer to exist.

The following are implemented with the unwrapped returned incomplete-computation value as Src:

ยงExamples
use rug::Integer;
let two = Integer::from(2);
let thousand = Integer::from(1000);
let minus_five = Integer::from(-5);
let seven = Integer::from(7);

// Modulo 1000, 2 has no inverse: there is no i such that 2 ร— i = 1.
assert!(two.pow_mod_ref(&minus_five, &thousand).is_none());

// 7 ร— 143 modulo 1000 = 1, so 7 has an inverse 143.
// 7 ^ -5 modulo 1000 = 143 ^ 5 modulo 1000 = 943.
let r = seven.pow_mod_ref(&minus_five, &thousand).unwrap();
let power = Integer::from(r);
assert_eq!(power, 943);
Source

pub fn secure_pow_mod_ref<'a>( &'a self, exponent: &'a Self, modulo: &'a Self, ) -> SecurePowModIncomplete<'a>

Raises a number to the power of exponent modulo modulo, with resilience to side-channel attacks.

The exponent must be greater than zero, and the modulo must be odd.

This method is intended for cryptographic purposes where resilience to side-channel attacks is desired. The function is designed to take the same time and use the same cache access patterns for same-sized arguments, assuming that the arguments are placed at the same position and the machine state is identical when starting.

The following are implemented with the returned incomplete-computation value as Src:

ยงPanics

Panics if exponent โ‰ค 0 or if modulo is even.

ยงExamples
use rug::Integer;
// 7 ^ 4 mod 13 = 9
let n = Integer::from(7);
let e = Integer::from(4);
let m = Integer::from(13);
let power = Integer::from(n.secure_pow_mod_ref(&e, &m));
assert_eq!(power, 9);
Source

pub fn root_ref(&self, n: u32) -> RootIncomplete<'_>

Computes the nth root and truncates the result.

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::Integer;
let i = Integer::from(1004);
assert_eq!(Integer::from(i.root_ref(3)), 10);
Source

pub fn root_rem_ref(&self, n: u32) -> RootRemIncomplete<'_>

Computes the nth root and returns the truncated root and the remainder.

The remainder is the original number minus the truncated root raised to the power of n.

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::{Assign, Complete, Integer};
let i = Integer::from(1004);
let mut root = Integer::new();
let mut rem = Integer::new();
// 1004 = 10^3 + 5
(&mut root, &mut rem).assign(i.root_rem_ref(3));
assert_eq!(root, 10);
assert_eq!(rem, 4);
// 1004 = 3^6 + 275
let (other_root, other_rem) = i.root_rem_ref(6).complete();
assert_eq!(other_root, 3);
assert_eq!(other_rem, 275);
Source

pub fn square_ref(&self) -> MulIncomplete<'_>

Computes the square.

The following are implemented with the returned incomplete-computation value as Src:

i.square_ref() produces the exact same result as &i * &i.

ยงExamples
use rug::Integer;
let i = Integer::from(13);
assert_eq!(Integer::from(i.square_ref()), 169);
Source

pub fn sqrt_ref(&self) -> SqrtIncomplete<'_>

Computes the square root and truncates the result.

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::Integer;
let i = Integer::from(104);
assert_eq!(Integer::from(i.sqrt_ref()), 10);
Source

pub fn sqrt_rem_ref(&self) -> SqrtRemIncomplete<'_>

Computes the square root and the remainder.

The remainder is the original number minus the truncated root squared.

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::{Assign, Integer};
let i = Integer::from(104);
let mut sqrt = Integer::new();
let mut rem = Integer::new();
let r = i.sqrt_rem_ref();
(&mut sqrt, &mut rem).assign(r);
assert_eq!(sqrt, 10);
assert_eq!(rem, 4);
let r = i.sqrt_rem_ref();
let (other_sqrt, other_rem) = <(Integer, Integer)>::from(r);
assert_eq!(other_sqrt, 10);
assert_eq!(other_rem, 4);
Source

pub fn is_probably_prime(&self, reps: u32) -> IsPrime

Determines wheter a number is prime.

This function uses some trial divisions, a Baille-PSW probable prime test, then repsย โˆ’ย 24 Miller-Rabin probabilistic primality tests.

ยงExamples
use rug::integer::IsPrime;
use rug::Integer;
let no = Integer::from(163 * 4003);
assert_eq!(no.is_probably_prime(30), IsPrime::No);
let yes = Integer::from(817_504_243);
assert_eq!(yes.is_probably_prime(30), IsPrime::Yes);
// 16_412_292_043_871_650_369 is actually a prime.
let probably = Integer::from(16_412_292_043_871_650_369_u64);
assert_eq!(probably.is_probably_prime(30), IsPrime::Probably);
Source

pub fn next_prime_ref(&self) -> NextPrimeIncomplete<'_>

Identifies primes using a probabilistic algorithm; the chance of a composite passing will be extremely small.

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::Integer;
let i = Integer::from(800_000_000);
let r = i.next_prime_ref();
let prime = Integer::from(r);
assert_eq!(prime, 800_000_011);
Source

pub fn prev_prime_ref(&self) -> PrevPrimeIncomplete<'_>

Identifies previous prime number using a probabilistic algorithm; the chance of a composite passing will be extremely small.

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::Integer;
let i = Integer::from(800_000_000);
let r = i.prev_prime_ref();
let prime = Integer::from(r);
assert_eq!(prime, 799_999_999);
Source

pub fn gcd_ref<'a>(&'a self, other: &'a Self) -> GcdIncomplete<'a>

Finds the greatest common divisor.

The result is always positive except when both inputs are zero.

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::Integer;
let a = Integer::from(100);
let b = Integer::from(125);
let r = a.gcd_ref(&b);
// gcd of 100, 125 is 25
assert_eq!(Integer::from(r), 25);
Source

pub fn gcd_u_ref(&self, other: u32) -> GcdUIncomplete<'_>

Finds the greatest common divisor.

The result is always positive except when both inputs are zero.

The following are implemented with the returned incomplete-computation value as Src:

The implementation of From<Src> for Option<u32> is useful to obtain the result as a u32 if it fits. If otherย >ย 0 , the result always fits. If the result does not fit, it is equal to the absolute value of self.

ยงExamples
use rug::Integer;
let i = Integer::from(100);
let r = i.gcd_u_ref(125);
// gcd of 100, 125 is 25
assert_eq!(Integer::from(r), 25);
let r = i.gcd_u_ref(125);
assert_eq!(Option::<u32>::from(r), Some(25));
Source

pub fn extended_gcd_ref<'a>(&'a self, other: &'a Self) -> GcdExtIncomplete<'a>

Finds the greatest common divisor (GCD) of the two inputs (self and other), and two coefficients to obtain the GCD from the two inputs.

The following are implemented with the returned incomplete-computation value as Src:

In the case that only one of the two coefficients is required, the following are also implemented:

The GCD is always positive except when both inputs are zero. If the inputs are a and b, then the GCD is g and the coefficients are s and t such that

a ร— s + b ร— t = g

The values s and t are chosen such that normally, |s|ย <ย |b|ย /ย (2g) and |t|ย <ย |a|ย /ย (2g), and these relations define s and t uniquely. There are a few exceptional cases:

  • If |a|ย =ย |b|, then sย =ย 0, tย =ย sgn(b).
  • Otherwise, if bย =ย 0 or |b|ย =ย 2g, then sย =ย sgn(a), and if aย =ย 0 or |a|ย =ย 2g, then tย =ย sgn(b).
ยงExamples
use rug::{Assign, Integer};
let a = Integer::from(4);
let b = Integer::from(6);
let r = a.extended_gcd_ref(&b);
let mut g = Integer::new();
let mut s = Integer::new();
let mut t = Integer::new();
(&mut g, &mut s, &mut t).assign(r);
assert_eq!(a, 4);
assert_eq!(b, 6);
assert_eq!(g, 2);
assert_eq!(s, -1);
assert_eq!(t, 1);

In the case that only one of the two coefficients is required, this can be achieved as follows:

use rug::{Assign, Integer};
let a = Integer::from(4);
let b = Integer::from(6);

// no t required
let (mut g1, mut s1) = (Integer::new(), Integer::new());
(&mut g1, &mut s1).assign(a.extended_gcd_ref(&b));
assert_eq!(g1, 2);
assert_eq!(s1, -1);

// no s required
let (mut g2, mut t2) = (Integer::new(), Integer::new());
(&mut g2, &mut t2).assign(b.extended_gcd_ref(&a));
assert_eq!(g2, 2);
assert_eq!(t2, 1);
Source

pub fn lcm_ref<'a>(&'a self, other: &'a Self) -> LcmIncomplete<'a>

Finds the least common multiple.

The result is always positive except when one or both inputs are zero.

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::Integer;
let a = Integer::from(100);
let b = Integer::from(125);
let r = a.lcm_ref(&b);
// lcm of 100, 125 is 500
assert_eq!(Integer::from(r), 500);
Source

pub fn lcm_u_ref(&self, other: u32) -> LcmUIncomplete<'_>

Finds the least common multiple.

The result is always positive except when one or both inputs are zero.

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::Integer;
let i = Integer::from(100);
let r = i.lcm_u_ref(125);
// lcm of 100, 125 is 500
assert_eq!(Integer::from(r), 500);
Source

pub fn jacobi(&self, n: &Self) -> i32

Calculates the Jacobi symbol (self/n).

ยงExamples
use rug::{Assign, Integer};
let m = Integer::from(10);
let mut n = Integer::from(13);
assert_eq!(m.jacobi(&n), 1);
n.assign(15);
assert_eq!(m.jacobi(&n), 0);
n.assign(17);
assert_eq!(m.jacobi(&n), -1);
Source

pub fn legendre(&self, p: &Self) -> i32

Calculates the Legendre symbol (self/p).

ยงExamples
use rug::{Assign, Integer};
let a = Integer::from(5);
let mut p = Integer::from(7);
assert_eq!(a.legendre(&p), -1);
p.assign(11);
assert_eq!(a.legendre(&p), 1);
Source

pub fn kronecker(&self, n: &Self) -> i32

Calculates the Jacobi symbol (self/n) with the Kronecker extension.

ยงExamples
use rug::{Assign, Integer};
let k = Integer::from(3);
let mut n = Integer::from(16);
assert_eq!(k.kronecker(&n), 1);
n.assign(17);
assert_eq!(k.kronecker(&n), -1);
n.assign(18);
assert_eq!(k.kronecker(&n), 0);
Source

pub fn remove_factor_ref<'a>( &'a self, factor: &'a Self, ) -> RemoveFactorIncomplete<'a>

Removes all occurrences of factor, and counts the number of occurrences removed.

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::{Assign, Integer};
let mut i = Integer::from(Integer::u_pow_u(13, 50));
i *= 1000;
let factor = Integer::from(13);
let r = i.remove_factor_ref(&factor);
let (mut j, mut count) = (Integer::new(), 0);
(&mut j, &mut count).assign(r);
assert_eq!(count, 50);
assert_eq!(j, 1000);
Source

pub fn binomial_ref(&self, k: u32) -> BinomialIncomplete<'_>

Computes the binomial coefficient over k.

The following are implemented with the returned incomplete-computation value as Src:

ยงExamples
use rug::{Complete, Integer};
// 7 choose 2 is 21
let i = Integer::from(7);
assert_eq!(i.binomial_ref(2).complete(), 21);
Source

pub fn random_below_ref<'a>( &'a self, rng: &'a mut dyn MutRandState, ) -> RandomBelowIncomplete<'a>

Generates a non-negative random number below the given boundary value.

The following are implemented with the returned incomplete-computation value as Src:

ยงPanics

Panics if the boundary value is less than or equal to zero.

ยงExamples
use rug::rand::RandState;
use rug::Integer;
let mut rand = RandState::new();
let bound = Integer::from(15);
let i = Integer::from(bound.random_below_ref(&mut rand));
println!("0 โ‰ค {} < {}", i, bound);
assert!(i < bound);
Source

pub fn gcd_cofactors_ref<'a>(&'a self, other: &'a Self) -> GcdExtIncomplete<'a>

๐Ÿ‘ŽDeprecated since 1.18.0: renamed to extended_gcd_ref

This method has been renamed to extended_gcd_ref.

Trait Implementationsยง

Sourceยง

impl Assign<&SmallInteger> for Integer

Sourceยง

fn assign(&mut self, src: &SmallInteger)

Peforms the assignement.
Sourceยง

impl Assign<&SmallInteger> for SmallInteger

Sourceยง

fn assign(&mut self, other: &Self)

Peforms the assignement.
Sourceยง

impl Assign<SmallInteger> for Integer

Sourceยง

fn assign(&mut self, src: SmallInteger)

Peforms the assignement.
Sourceยง

impl<T: ToSmall> Assign<T> for SmallInteger

Sourceยง

fn assign(&mut self, src: T)

Peforms the assignement.
Sourceยง

impl Assign for SmallInteger

Sourceยง

fn assign(&mut self, other: Self)

Peforms the assignement.
Sourceยง

impl Clone for SmallInteger

Sourceยง

fn clone(&self) -> SmallInteger

Returns a duplicate of the value. Read more
1.0.0 ยท Sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Sourceยง

impl Debug for SmallInteger

Sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult

Formats the value using the given formatter. Read more
Sourceยง

impl Default for SmallInteger

Sourceยง

fn default() -> Self

Returns the โ€œdefault valueโ€ for a type. Read more
Sourceยง

impl Deref for SmallInteger

Sourceยง

type Target = Integer

The resulting type after dereferencing.
Sourceยง

fn deref(&self) -> &Integer

Dereferences the value.
Sourceยง

impl From<&SmallInteger> for Integer

Sourceยง

fn from(src: &SmallInteger) -> Self

Converts to this type from the input type.
Sourceยง

impl From<SmallInteger> for Integer

Sourceยง

fn from(src: SmallInteger) -> Self

Converts to this type from the input type.
Sourceยง

impl<T: ToSmall> From<T> for SmallInteger

Sourceยง

fn from(src: T) -> Self

Converts to this type from the input type.
Sourceยง

impl PartialEq<Integer> for SmallInteger

Sourceยง

fn eq(&self, other: &Integer) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 ยท Sourceยง

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Sourceยง

impl PartialEq<SmallInteger> for Integer

Sourceยง

fn eq(&self, other: &SmallInteger) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 ยท Sourceยง

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Sourceยง

impl PartialOrd<Integer> for SmallInteger

Sourceยง

fn partial_cmp(&self, other: &Integer) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 ยท Sourceยง

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 ยท Sourceยง

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 ยท Sourceยง

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 ยท Sourceยง

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Sourceยง

impl PartialOrd<SmallInteger> for Integer

Sourceยง

fn partial_cmp(&self, other: &SmallInteger) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 ยท Sourceยง

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 ยท Sourceยง

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 ยท Sourceยง

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 ยท Sourceยง

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Sourceยง

impl Send for SmallInteger

Auto Trait Implementationsยง

Blanket Implementationsยง

Sourceยง

impl<T> Any for T
where T: 'static + ?Sized,

Sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Sourceยง

impl<T> Az for T

Sourceยง

fn az<Dst>(self) -> Dst
where T: Cast<Dst>,

Casts the value.
Sourceยง

impl<T> Borrow<T> for T
where T: ?Sized,

Sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Sourceยง

impl<T> BorrowMut<T> for T
where T: ?Sized,

Sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Sourceยง

impl<Src, Dst> CastFrom<Src> for Dst
where Src: Cast<Dst>,

Sourceยง

fn cast_from(src: Src) -> Dst

Casts the value.
Sourceยง

impl<T> CheckedAs for T

Sourceยง

fn checked_as<Dst>(self) -> Option<Dst>
where T: CheckedCast<Dst>,

Casts the value.
Sourceยง

impl<Src, Dst> CheckedCastFrom<Src> for Dst
where Src: CheckedCast<Dst>,

Sourceยง

fn checked_cast_from(src: Src) -> Option<Dst>

Casts the value.
Sourceยง

impl<T> CloneToUninit for T
where T: Clone,

Sourceยง

unsafe fn clone_to_uninit(&self, dest: *mut u8)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Sourceยง

impl<T> From<T> for T

Sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

Sourceยง

impl<T, U> Into<U> for T
where U: From<T>,

Sourceยง

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Sourceยง

impl<T> OverflowingAs for T

Sourceยง

fn overflowing_as<Dst>(self) -> (Dst, bool)
where T: OverflowingCast<Dst>,

Casts the value.
Sourceยง

impl<Src, Dst> OverflowingCastFrom<Src> for Dst
where Src: OverflowingCast<Dst>,

Sourceยง

fn overflowing_cast_from(src: Src) -> (Dst, bool)

Casts the value.
Sourceยง

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Sourceยง

type Target = T

๐Ÿ”ฌThis is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Sourceยง

impl<T> SaturatingAs for T

Sourceยง

fn saturating_as<Dst>(self) -> Dst
where T: SaturatingCast<Dst>,

Casts the value.
Sourceยง

impl<Src, Dst> SaturatingCastFrom<Src> for Dst
where Src: SaturatingCast<Dst>,

Sourceยง

fn saturating_cast_from(src: Src) -> Dst

Casts the value.
Sourceยง

impl<T> ToOwned for T
where T: Clone,

Sourceยง

type Owned = T

The resulting type after obtaining ownership.
Sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Sourceยง

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
Sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Sourceยง

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Sourceยง

impl<T> UnwrappedAs for T

Sourceยง

fn unwrapped_as<Dst>(self) -> Dst
where T: UnwrappedCast<Dst>,

Casts the value.
Sourceยง

impl<Src, Dst> UnwrappedCastFrom<Src> for Dst
where Src: UnwrappedCast<Dst>,

Sourceยง

fn unwrapped_cast_from(src: Src) -> Dst

Casts the value.
Sourceยง

impl<T> WrappingAs for T

Sourceยง

fn wrapping_as<Dst>(self) -> Dst
where T: WrappingCast<Dst>,

Casts the value.
Sourceยง

impl<Src, Dst> WrappingCastFrom<Src> for Dst
where Src: WrappingCast<Dst>,

Sourceยง

fn wrapping_cast_from(src: Src) -> Dst

Casts the value.