rug/integer/big.rs
1// Copyright © 2016–2025 Trevor Spiteri
2
3// This program is free software: you can redistribute it and/or modify it under
4// the terms of the GNU Lesser General Public License as published by the Free
5// Software Foundation, either version 3 of the License, or (at your option) any
6// later version.
7//
8// This program is distributed in the hope that it will be useful, but WITHOUT
9// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
10// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
11// details.
12//
13// You should have received a copy of the GNU Lesser General Public License and
14// a copy of the GNU General Public License along with this program. If not, see
15// <https://www.gnu.org/licenses/>.
16
17use crate::ext::xmpz;
18use crate::integer::arith::MulIncomplete;
19use crate::integer::{BorrowInteger, MiniInteger, Order};
20use crate::misc;
21use crate::misc::{StringLike, VecLike};
22use crate::ops::{DivRounding, NegAssign, SubFrom};
23#[cfg(feature = "rand")]
24use crate::rand::MutRandState;
25#[cfg(feature = "rational")]
26use crate::rational::BorrowRational;
27use crate::{Assign, Complete};
28use az::{Az, Cast, CheckedCast, UnwrappedAs, UnwrappedCast, WrappingCast};
29use core::cmp::Ordering;
30use core::ffi::{c_uint, c_ulong};
31use core::fmt::{Display, Formatter, Result as FmtResult};
32use core::mem;
33use core::mem::{ManuallyDrop, MaybeUninit};
34use core::ops::{Add, AddAssign, Mul, MulAssign, Sub, SubAssign};
35#[cfg(feature = "rational")]
36use core::ptr::NonNull;
37use core::slice;
38use gmp_mpfr_sys::gmp;
39#[cfg(feature = "rational")]
40use gmp_mpfr_sys::gmp::mpq_t;
41use gmp_mpfr_sys::gmp::{bitcnt_t, limb_t, mpz_t};
42#[cfg(feature = "std")]
43use std::error::Error;
44
45/**
46An arbitrary-precision integer.
47
48Standard arithmetic operations, bitwise operations and comparisons are
49supported. In standard arithmetic operations such as addition, you can mix
50`Integer` and primitive integer types; the result will be an `Integer`.
51
52Internally the integer is not stored using a two’s-complement representation,
53however, for bitwise operations and shifts, the functionality is the same as if
54the representation was using two’s complement.
55
56# Examples
57
58```rust
59use rug::{Assign, Integer};
60// Create an integer initialized as zero.
61let mut int = Integer::new();
62assert_eq!(int, 0);
63assert_eq!(int.to_u32(), Some(0));
64int.assign(-14);
65assert_eq!(int, -14);
66assert_eq!(int.to_u32(), None);
67assert_eq!(int.to_i32(), Some(-14));
68```
69
70Arithmetic operations with mixed arbitrary and primitive types are allowed. Note
71that in the following example, there is only one allocation. The `Integer`
72instance is moved into the shift operation so that the result can be stored in
73the same instance, then that result is similarly consumed by the addition
74operation.
75
76```rust
77use rug::Integer;
78let mut a = Integer::from(0xc);
79a = (a << 80) + 0xffee;
80assert_eq!(a.to_string_radix(16), "c0000000000000000ffee");
81// ↑ ↑ ↑ ↑ ↑ ↑
82// 80 64 48 32 16 0
83```
84
85Bitwise operations on `Integer` values behave as if the value uses a
86two’s-complement representation.
87
88```rust
89use rug::Integer;
90
91let mut i = Integer::from(1);
92i = i << 1000;
93// i is now 1000000... (1000 zeros)
94assert_eq!(i.significant_bits(), 1001);
95assert_eq!(i.find_one(0), Some(1000));
96i -= 1;
97// i is now 111111... (1000 ones)
98assert_eq!(i.count_ones(), Some(1000));
99
100let a = Integer::from(0xf00d);
101// -1 is all ones in two’s complement
102let all_ones_xor_a = Integer::from(-1 ^ &a);
103// a is unchanged as we borrowed it
104let complement_a = !a;
105// now a has been moved, so this would cause an error:
106// assert!(a > 0);
107assert_eq!(all_ones_xor_a, complement_a);
108assert_eq!(complement_a, -0xf00e);
109assert_eq!(format!("{:x}", complement_a), "-f00e");
110```
111
112To initialize a large `Integer` that does not fit in a primitive type, you can
113parse a string.
114
115```rust
116use rug::Integer;
117let s1 = "123456789012345678901234567890";
118let i1 = s1.parse::<Integer>().unwrap();
119assert_eq!(i1.significant_bits(), 97);
120let s2 = "ffff0000ffff0000ffff0000ffff0000ffff0000";
121let i2 = Integer::from_str_radix(s2, 16).unwrap();
122assert_eq!(i2.significant_bits(), 160);
123assert_eq!(i2.count_ones(), Some(80));
124```
125
126Operations on two borrowed `Integer` values result in an [incomplete-computation
127value][icv] that has to be assigned to a new `Integer` value.
128
129```rust
130use rug::Integer;
131let a = Integer::from(10);
132let b = Integer::from(3);
133let a_b_ref = &a + &b;
134let a_b = Integer::from(a_b_ref);
135assert_eq!(a_b, 13);
136```
137
138As a special case, when an [incomplete-computation value][icv] is obtained from
139multiplying two `Integer` references, it can be added to or subtracted from
140another `Integer` (or reference). This can be useful for multiply-accumulate
141operations.
142
143```rust
144use rug::Integer;
145let mut acc = Integer::from(100);
146let m1 = Integer::from(3);
147let m2 = Integer::from(7);
148// 100 + 3 × 7 = 121
149acc += &m1 * &m2;
150assert_eq!(acc, 121);
151let other = Integer::from(2000);
152// Do not consume any values here:
153// 2000 - 3 × 7 = 1979
154let sub = Integer::from(&other - &m1 * &m2);
155assert_eq!(sub, 1979);
156```
157
158The `Integer` type supports various functions. Most methods have three versions:
159
160 1. The first method consumes the operand.
161 2. The second method has a “`_mut`” suffix and mutates the operand.
162 3. The third method has a “`_ref`” suffix and borrows the operand. The returned
163 item is an [incomplete-computation value][icv] that can be assigned to an
164 `Integer`.
165
166```rust
167use rug::Integer;
168
169// 1. consume the operand
170let a = Integer::from(-15);
171let abs_a = a.abs();
172assert_eq!(abs_a, 15);
173
174// 2. mutate the operand
175let mut b = Integer::from(-16);
176b.abs_mut();
177assert_eq!(b, 16);
178
179// 3. borrow the operand
180let c = Integer::from(-17);
181let r = c.abs_ref();
182let abs_c = Integer::from(r);
183assert_eq!(abs_c, 17);
184// c was not consumed
185assert_eq!(c, -17);
186```
187
188[icv]: crate#incomplete-computation-values
189*/
190#[repr(transparent)]
191pub struct Integer {
192 inner: mpz_t,
193}
194
195impl Integer {
196 #[inline]
197 pub(crate) const fn inner(&self) -> &mpz_t {
198 &self.inner
199 }
200 #[inline]
201 pub(crate) unsafe fn inner_mut(&mut self) -> &mut mpz_t {
202 &mut self.inner
203 }
204 #[inline]
205 pub(crate) const fn inner_data(&self) -> &[limb_t] {
206 let limbs = self.inner.size.unsigned_abs();
207 let limbs_usize = limbs as usize;
208 if limbs != limbs_usize as c_uint {
209 panic!("overflow");
210 }
211 unsafe { slice::from_raw_parts(self.inner.d.as_ptr(), limbs_usize) }
212 }
213}
214
215static_assert_same_layout!(Integer, mpz_t);
216static_assert_same_layout!(BorrowInteger<'_>, mpz_t);
217
218static_assert_same_size!(Integer, Option<Integer>);
219
220impl Integer {
221 /// Zero.
222 ///
223 /// # Examples
224 ///
225 /// ```rust
226 /// use rug::Integer;
227 /// assert_eq!(Integer::ZERO, 0);
228 /// ```
229 pub const ZERO: Integer = Integer::new();
230
231 /// One.
232 ///
233 /// # Examples
234 ///
235 /// ```rust
236 /// use rug::Integer;
237 /// assert_eq!(*Integer::ONE, 1);
238 /// ```
239 pub const ONE: &'static Integer = {
240 const MINI: MiniInteger = MiniInteger::const_from_bool(true);
241 const BORROW: BorrowInteger = MINI.borrow();
242 BorrowInteger::const_deref(&BORROW)
243 };
244
245 /// Negative one (−1).
246 ///
247 /// # Examples
248 ///
249 /// ```rust
250 /// use rug::Integer;
251 /// assert_eq!(*Integer::NEG_ONE, -1);
252 /// ```
253 pub const NEG_ONE: &'static Integer = {
254 const BORROW: BorrowInteger = Integer::ONE.as_neg();
255 BorrowInteger::const_deref(&BORROW)
256 };
257
258 /// Constructs a new arbitrary-precision [`Integer`] with value 0.
259 ///
260 /// The created [`Integer`] will have no allocated memory yet.
261 ///
262 /// # Examples
263 ///
264 /// ```rust
265 /// use rug::Integer;
266 /// let i = Integer::new();
267 /// assert_eq!(i, 0);
268 /// ```
269 #[inline]
270 pub const fn new() -> Self {
271 Integer {
272 inner: xmpz::owned_init(),
273 }
274 }
275
276 /// Constructs a new arbitrary-precision [`Integer`] with at least the
277 /// specified capacity.
278 ///
279 /// # Examples
280 ///
281 /// ```rust
282 /// use rug::Integer;
283 /// let i = Integer::with_capacity(137);
284 /// assert!(i.capacity() >= 137);
285 /// ```
286 #[inline]
287 pub fn with_capacity(bits: usize) -> Self {
288 unsafe {
289 let mut dst = MaybeUninit::uninit();
290 xmpz::init2(dst.as_mut_ptr(), bits);
291 dst.assume_init()
292 }
293 }
294
295 /// Returns the capacity in bits that can be stored without reallocating.
296 ///
297 /// # Examples
298 ///
299 /// ```rust
300 /// use rug::Integer;
301 /// let i = Integer::with_capacity(137);
302 /// assert!(i.capacity() >= 137);
303 /// ```
304 #[inline]
305 pub fn capacity(&self) -> usize {
306 self.inner
307 .alloc
308 .unwrapped_as::<usize>()
309 .checked_mul(gmp::LIMB_BITS.az::<usize>())
310 .expect("overflow")
311 }
312
313 /// Reserves capacity for at least `additional` more bits in the
314 /// [`Integer`].
315 ///
316 /// If the integer already has enough excess capacity, this function does
317 /// nothing.
318 ///
319 /// # Examples
320 ///
321 /// ```rust
322 /// use rug::Integer;
323 /// // 0x2000_0000 needs 30 bits.
324 /// let mut i = Integer::from(0x2000_0000);
325 /// assert_eq!(i.significant_bits(), 30);
326 /// i.reserve(290);
327 /// let capacity = i.capacity();
328 /// assert!(capacity >= 320);
329 /// i.reserve(0);
330 /// assert_eq!(i.capacity(), capacity);
331 /// i.reserve(291);
332 /// assert!(i.capacity() >= 321);
333 /// ```
334 pub fn reserve(&mut self, additional: usize) {
335 let used_bits = xmpz::significant_bits(self);
336 let req_bits = used_bits.checked_add(additional).expect("overflow");
337 let alloc_bits = (self.inner.alloc.az::<usize>())
338 .checked_mul(gmp::LIMB_BITS.az::<usize>())
339 .expect("overflow");
340 if alloc_bits < req_bits {
341 unsafe {
342 gmp::mpz_realloc2(self.as_raw_mut(), req_bits.unwrapped_cast());
343 }
344 }
345 }
346
347 /// Shrinks the capacity of the [`Integer`] as much as possible.
348 ///
349 /// The capacity can still be larger than the number of significant bits.
350 ///
351 /// # Examples
352 ///
353 /// ```rust
354 /// use rug::Integer;
355 /// // let i be 100 bits wide
356 /// let mut i = Integer::from_str_radix("fffff12345678901234567890", 16)
357 /// .unwrap();
358 /// assert_eq!(i.significant_bits(), 100);
359 /// assert!(i.capacity() >= 100);
360 /// i >>= 80;
361 /// i.shrink_to_fit();
362 /// assert!(i.capacity() >= 20);
363 /// ```
364 pub fn shrink_to_fit(&mut self) {
365 self.shrink_to(0);
366 }
367
368 /// Shrinks the capacity of the [`Integer`] with a lower bound in bits.
369 ///
370 /// The capacity will remain at least as large as both the current number of
371 /// siginificant bits and the supplied value.
372 ///
373 /// If the current capacity is less than the lower limit, this method has no
374 /// effect.
375 ///
376 /// # Examples
377 ///
378 /// ```rust
379 /// use rug::Integer;
380 /// // let i be 100 bits wide
381 /// let mut i = Integer::from_str_radix("fffff12345678901234567890", 16)
382 /// .unwrap();
383 /// assert_eq!(i.significant_bits(), 100);
384 /// assert!(i.capacity() >= 100);
385 /// i >>= 80;
386 /// i.shrink_to(50);
387 /// assert!(i.capacity() >= 50);
388 /// i.shrink_to(0);
389 /// assert!(i.capacity() >= 20);
390 /// ```
391 pub fn shrink_to(&mut self, min_capacity: usize) {
392 let min_limbs = DivRounding::div_ceil(min_capacity, gmp::LIMB_BITS.az::<usize>());
393 if min_limbs >= self.inner.alloc.unwrapped_as::<usize>() {
394 return;
395 }
396 let used_limbs = self.inner.size.checked_abs().expect("overflow");
397 if min_limbs > used_limbs.unwrapped_as::<usize>() {
398 // we already know that self.inner.alloc > min_limbs
399 // and that min_limbs > 0
400 unsafe {
401 gmp::_mpz_realloc(self.as_raw_mut(), min_limbs.unwrapped_cast());
402 }
403 } else if self.inner.alloc > used_limbs {
404 if used_limbs == 0 {
405 *self = Integer::ZERO;
406 } else {
407 unsafe {
408 gmp::_mpz_realloc(self.as_raw_mut(), used_limbs.unwrapped_cast());
409 }
410 }
411 }
412 }
413
414 /// Creates an [`Integer`] from an initialized [GMP integer][mpz_t].
415 ///
416 /// # Safety
417 ///
418 /// * The function must *not* be used to create a constant [`Integer`],
419 /// though it can be used to create a static [`Integer`]. This is
420 /// because constant values are *copied* on use, leading to undefined
421 /// behavior when they are dropped.
422 /// * The value must be initialized as a valid [`mpz_t`].
423 /// * The [`mpz_t`] type can be considered as a kind of pointer, so there
424 /// can be multiple copies of it. Since this function takes over
425 /// ownership, no other copies of the passed value should exist.
426 ///
427 /// # Examples
428 ///
429 /// ```rust
430 /// use core::mem::MaybeUninit;
431 /// use gmp_mpfr_sys::gmp;
432 /// use rug::Integer;
433 /// let i = unsafe {
434 /// let mut z = MaybeUninit::uninit();
435 /// gmp::mpz_init_set_ui(z.as_mut_ptr(), 15);
436 /// let z = z.assume_init();
437 /// // z is initialized and unique
438 /// Integer::from_raw(z)
439 /// };
440 /// assert_eq!(i, 15);
441 /// // since i is an Integer now, deallocation is automatic
442 /// ```
443 ///
444 /// This can be used to create a static [`Integer`] using
445 /// [`MPZ_ROINIT_N`][gmp::MPZ_ROINIT_N] to initialize the raw value. See the
446 /// [GMP documentation][gmp roinit] for details.
447 ///
448 /// ```rust
449 /// use gmp_mpfr_sys::gmp;
450 /// use gmp_mpfr_sys::gmp::{limb_t, mpz_t};
451 /// use rug::Integer;
452 /// const LIMBS: [limb_t; 2] = [123, 456];
453 /// const MPZ: mpz_t =
454 /// unsafe { gmp::MPZ_ROINIT_N(LIMBS.as_ptr().cast_mut(), -2) };
455 /// // Must *not* be const, otherwise it would lead to undefined
456 /// // behavior on use, as it would create a copy that is dropped.
457 /// static I: Integer = unsafe { Integer::from_raw(MPZ) };
458 /// let check = -((Integer::from(LIMBS[1]) << gmp::NUMB_BITS) + LIMBS[0]);
459 /// assert_eq!(I, check);
460 /// ```
461 ///
462 /// [gmp roinit]: gmp_mpfr_sys::C::GMP::Integer_Functions#index-MPZ_005fROINIT_005fN
463 #[inline]
464 pub const unsafe fn from_raw(raw: mpz_t) -> Self {
465 Integer { inner: raw }
466 }
467
468 /// Converts an [`Integer`] into a [GMP integer][mpz_t].
469 ///
470 /// The returned object should be freed to avoid memory leaks.
471 ///
472 /// # Examples
473 ///
474 /// ```rust
475 /// use gmp_mpfr_sys::gmp;
476 /// use rug::Integer;
477 /// let i = Integer::from(15);
478 /// let mut z = i.into_raw();
479 /// unsafe {
480 /// let u = gmp::mpz_get_ui(&z);
481 /// assert_eq!(u, 15);
482 /// // free object to prevent memory leak
483 /// gmp::mpz_clear(&mut z);
484 /// }
485 /// ```
486 #[inline]
487 pub const fn into_raw(self) -> mpz_t {
488 let ret = self.inner;
489 let _ = ManuallyDrop::new(self);
490 ret
491 }
492
493 /// Returns a pointer to the inner [GMP integer][mpz_t].
494 ///
495 /// The returned pointer will be valid for as long as `self` is valid.
496 ///
497 /// # Examples
498 ///
499 /// ```rust
500 /// use gmp_mpfr_sys::gmp;
501 /// use rug::Integer;
502 /// let i = Integer::from(15);
503 /// let z_ptr = i.as_raw();
504 /// unsafe {
505 /// let u = gmp::mpz_get_ui(z_ptr);
506 /// assert_eq!(u, 15);
507 /// }
508 /// // i is still valid
509 /// assert_eq!(i, 15);
510 /// ```
511 #[inline]
512 pub const fn as_raw(&self) -> *const mpz_t {
513 &self.inner
514 }
515
516 /// Returns an unsafe mutable pointer to the inner [GMP integer][mpz_t].
517 ///
518 /// The returned pointer will be valid for as long as `self` is valid.
519 ///
520 /// # Examples
521 ///
522 /// ```rust
523 /// use gmp_mpfr_sys::gmp;
524 /// use rug::Integer;
525 /// let mut i = Integer::from(15);
526 /// let z_ptr = i.as_raw_mut();
527 /// unsafe {
528 /// gmp::mpz_add_ui(z_ptr, z_ptr, 20);
529 /// }
530 /// assert_eq!(i, 35);
531 /// ```
532 #[inline]
533 pub fn as_raw_mut(&mut self) -> *mut mpz_t {
534 &mut self.inner
535 }
536
537 /// Creates an [`Integer`] from a [slice] of digits of type `T`, where `T`
538 /// can be any [unsigned integer primitive type][UnsignedPrimitive].
539 ///
540 /// The resulting value cannot be negative.
541 ///
542 /// # Examples
543 ///
544 /// ```rust
545 /// use rug::integer::Order;
546 /// use rug::Integer;
547 /// let digits = [0x5678u16, 0x1234u16];
548 /// let i = Integer::from_digits(&digits, Order::Lsf);
549 /// assert_eq!(i, 0x1234_5678);
550 /// ```
551 ///
552 /// [slice]: prim@slice
553 pub fn from_digits<T: UnsignedPrimitive>(digits: &[T], order: Order) -> Self {
554 let capacity = digits.len().checked_mul(T::PRIVATE.bits).expect("overflow");
555 let mut i = Integer::with_capacity(capacity);
556 i.assign_digits(digits, order);
557 i
558 }
559
560 /// Assigns from a [slice] of digits of type `T`, where `T` can be any
561 /// [unsigned integer primitive type][UnsignedPrimitive].
562 ///
563 /// The resulting value cannot be negative.
564 ///
565 /// # Examples
566 ///
567 /// ```rust
568 /// use rug::integer::Order;
569 /// use rug::Integer;
570 /// let digits = [0x5678u16, 0x1234u16];
571 /// let mut i = Integer::new();
572 /// i.assign_digits(&digits, Order::Lsf);
573 /// assert_eq!(i, 0x1234_5678);
574 /// ```
575 ///
576 /// [slice]: prim@slice
577 pub fn assign_digits<T: UnsignedPrimitive>(&mut self, digits: &[T], order: Order) {
578 // Safety: it is valid to read digits.len() digits from digits.as_mut_ptr().
579 unsafe {
580 self.assign_digits_unaligned(digits.as_ptr(), digits.len(), order);
581 }
582 }
583
584 /// Assigns from digits of type `T` in a memory area, where `T` can be any
585 /// [unsigned integer primitive type][UnsignedPrimitive].
586 ///
587 /// The memory area is addressed using a pointer and a length. The `len`
588 /// parameter is the number of digits, *not* the number of bytes.
589 ///
590 /// There are no data alignment restrictions on `src`, any address is
591 /// allowed.
592 ///
593 /// The resulting value cannot be negative.
594 ///
595 /// # Safety
596 ///
597 /// To avoid undefined behavior, `src` must be [valid] for reading `len`
598 /// digits, that is `len` × `size_of::<T>()` bytes.
599 ///
600 /// # Examples
601 ///
602 /// ```rust
603 /// use rug::integer::Order;
604 /// use rug::Integer;
605 /// // hex bytes: [ fe dc ba 98 87 87 87 87 76 54 32 10 ]
606 /// let digits = [
607 /// 0xfedc_ba98u32.to_be(),
608 /// 0x8787_8787u32.to_be(),
609 /// 0x7654_3210u32.to_be(),
610 /// ];
611 /// let ptr = digits.as_ptr();
612 /// let mut i = Integer::new();
613 /// unsafe {
614 /// let unaligned = (ptr.cast::<u8>()).offset(2).cast::<u32>();
615 /// i.assign_digits_unaligned(unaligned, 2, Order::MsfBe);
616 /// }
617 /// assert_eq!(i, 0xba98_8787_8787_7654u64);
618 /// ```
619 ///
620 /// [valid]: core::ptr#safety
621 pub unsafe fn assign_digits_unaligned<T: UnsignedPrimitive>(
622 &mut self,
623 src: *const T,
624 len: usize,
625 order: Order,
626 ) {
627 let bytes = mem::size_of::<T>();
628 let nails = 8 * bytes - T::PRIVATE.bits;
629 let raw = self.as_raw_mut();
630 let (order, endian) = (order.order(), order.endian());
631 let src = src.cast();
632 unsafe {
633 gmp::mpz_import(raw, len, order, bytes, endian, nails, src);
634 }
635 }
636
637 /// Returns the number of digits of type `T` required to represent the
638 /// absolute value.
639 ///
640 /// `T` can be any [unsigned integer primitive type][UnsignedPrimitive].
641 ///
642 /// # Examples
643 ///
644 /// ```rust
645 /// use rug::Integer;
646 ///
647 /// let i: Integer = Integer::from(1) << 256;
648 /// assert_eq!(i.significant_digits::<bool>(), 257);
649 /// assert_eq!(i.significant_digits::<u8>(), 33);
650 /// assert_eq!(i.significant_digits::<u16>(), 17);
651 /// assert_eq!(i.significant_digits::<u32>(), 9);
652 /// assert_eq!(i.significant_digits::<u64>(), 5);
653 /// ```
654 #[inline]
655 pub fn significant_digits<T: UnsignedPrimitive>(&self) -> usize {
656 DivRounding::div_ceil(xmpz::significant_bits(self), T::PRIVATE.bits)
657 }
658
659 /// Converts the absolute value to a [`Vec`] of digits of type `T`, where
660 /// `T` can be any [unsigned integer primitive type][UnsignedPrimitive].
661 ///
662 /// The [`Integer`] type also has the [`as_limbs`][Integer::as_limbs]
663 /// method, which can be used to borrow the digits without copying them.
664 /// This does come with some more constraints compared to `to_digits`:
665 ///
666 /// 1. The digit width is not optional and depends on the implementation:
667 /// [`limb_t`] is typically [`u64`] on 64-bit systems and [`u32`] on
668 /// 32-bit systems.
669 /// 2. The order is not optional and is least significant digit first, with
670 /// each digit in the target’s endianness, equivalent to
671 /// <code>[Order]::[Lsf][Order::Lsf]</code>.
672 ///
673 /// # Examples
674 ///
675 /// ```rust
676 /// use rug::integer::Order;
677 /// use rug::Integer;
678 /// let i = Integer::from(0x1234_5678_9abc_def0u64);
679 /// let digits = i.to_digits::<u32>(Order::MsfBe);
680 /// assert_eq!(digits, [0x1234_5678u32.to_be(), 0x9abc_def0u32.to_be()]);
681 ///
682 /// let zero = Integer::new();
683 /// let digits_zero = zero.to_digits::<u32>(Order::MsfBe);
684 /// assert!(digits_zero.is_empty());
685 /// ```
686 #[cfg(feature = "std")]
687 pub fn to_digits<T: UnsignedPrimitive>(&self, order: Order) -> Vec<T> {
688 let digit_count = self.significant_digits::<T>();
689 let mut v = Vec::<T>::with_capacity(digit_count);
690 unsafe {
691 let digits_ptr = v.as_mut_ptr();
692 let mut count = MaybeUninit::uninit();
693 gmp::mpz_export(
694 digits_ptr.cast(),
695 count.as_mut_ptr(),
696 order.order(),
697 T::PRIVATE.bytes,
698 order.endian(),
699 T::PRIVATE.nails,
700 self.as_raw(),
701 );
702 assert_eq!(count.assume_init(), digit_count);
703 v.set_len(digit_count);
704 }
705 v
706 }
707
708 /// Writes the absolute value into a [slice] of digits of type `T`, where
709 /// `T` can be any [unsigned integer primitive type][UnsignedPrimitive].
710 ///
711 /// The slice must be large enough to hold the digits; the minimum size can
712 /// be obtained using the [`significant_digits`] method.
713 ///
714 /// # Panics
715 ///
716 /// Panics if the slice does not have sufficient capacity.
717 ///
718 /// # Examples
719 ///
720 /// ```rust
721 /// use rug::integer::Order;
722 /// use rug::Integer;
723 /// let i = Integer::from(0x1234_5678_9abc_def0u64);
724 /// let mut digits = [0xffff_ffffu32; 4];
725 /// i.write_digits(&mut digits, Order::MsfBe);
726 /// let word0 = 0x9abc_def0u32;
727 /// let word1 = 0x1234_5678u32;
728 /// assert_eq!(digits, [0, 0, word1.to_be(), word0.to_be()]);
729 /// ```
730 ///
731 /// [`significant_digits`]: `Integer::significant_digits`
732 /// [slice]: prim@slice
733 pub fn write_digits<T: UnsignedPrimitive>(&self, digits: &mut [T], order: Order) {
734 // Safety: it is valid to write digits.len() digits into digits.as_mut_ptr().
735 unsafe {
736 self.write_digits_unaligned(digits.as_mut_ptr(), digits.len(), order);
737 }
738 }
739
740 /// Writes the absolute value into a memory area of digits of type `T`,
741 /// where `T` can be any [unsigned integer primitive
742 /// type][UnsignedPrimitive].
743 ///
744 /// The memory area is addressed using a pointer and a length. The `len`
745 /// parameter is the number of digits, *not* the number of bytes.
746 ///
747 /// The length must be large enough to hold the digits; the minimum length
748 /// can be obtained using the [`significant_digits`] method.
749 ///
750 /// There are no data alignment restrictions on `dst`, any address is
751 /// allowed.
752 ///
753 /// The memory locations can be uninitialized before this method is called;
754 /// this method sets all `len` elements, padding with zeros if the length is
755 /// larger than required.
756 ///
757 /// # Safety
758 ///
759 /// To avoid undefined behavior, `dst` must be [valid] for writing `len`
760 /// digits, that is `len` × `size_of::<T>()` bytes.
761 ///
762 /// # Panics
763 ///
764 /// Panics if the length is less than the number of digits.
765 ///
766 /// # Examples
767 ///
768 /// ```rust
769 /// use rug::integer::Order;
770 /// use rug::Integer;
771 /// let i = Integer::from(0xfedc_ba98_7654_3210u64);
772 /// let mut digits = [0xffff_ffffu32; 4];
773 /// let ptr = digits.as_mut_ptr();
774 /// unsafe {
775 /// let unaligned = (ptr.cast::<u8>()).offset(2).cast::<u32>();
776 /// i.write_digits_unaligned(unaligned, 3, Order::MsfBe);
777 /// }
778 /// assert_eq!(
779 /// digits,
780 /// [
781 /// 0xffff_0000u32.to_be(),
782 /// 0x0000_fedcu32.to_be(),
783 /// 0xba98_7654u32.to_be(),
784 /// 0x3210_ffffu32.to_be(),
785 /// ]
786 /// );
787 /// ```
788 ///
789 /// The following example shows how to write into uninitialized memory. In
790 /// practice, the following code could be replaced by a call to the safe
791 /// method [`to_digits`].
792 ///
793 /// ```rust
794 /// use rug::integer::Order;
795 /// use rug::Integer;
796 /// let i = Integer::from(0x1234_5678_9abc_def0u64);
797 /// let len = i.significant_digits::<u32>();
798 /// assert_eq!(len, 2);
799 ///
800 /// // The following code is equivalent to:
801 /// // let digits = i.to_digits::<u32>(Order::MsfBe);
802 /// let mut digits = Vec::<u32>::with_capacity(len);
803 /// let ptr = digits.as_mut_ptr();
804 /// unsafe {
805 /// i.write_digits_unaligned(ptr, len, Order::MsfBe);
806 /// digits.set_len(len);
807 /// }
808 ///
809 /// assert_eq!(digits, [0x1234_5678u32.to_be(), 0x9abc_def0u32.to_be()]);
810 /// ```
811 ///
812 /// [`significant_digits`]: `Integer::significant_digits`
813 /// [`to_digits`]: `Integer::to_digits`
814 /// [valid]: `core::ptr`#safety
815 pub unsafe fn write_digits_unaligned<T: UnsignedPrimitive>(
816 &self,
817 dst: *mut T,
818 len: usize,
819 order: Order,
820 ) {
821 let digit_count = self.significant_digits::<T>();
822 let zero_count = len.checked_sub(digit_count).expect("not enough capacity");
823 let zero_bytes = zero_count * T::PRIVATE.bytes;
824 let (zeros, digits) = if order.order() < 0 {
825 let offset = digit_count.unwrapped_cast();
826 (unsafe { dst.offset(offset) }, dst)
827 } else {
828 let offset = zero_count.unwrapped_cast();
829 (dst, unsafe { dst.offset(offset) })
830 };
831 unsafe {
832 // use *mut u8 to allow for unaligned pointers
833 (zeros.cast::<u8>()).write_bytes(0, zero_bytes);
834 }
835 let mut count = MaybeUninit::uninit();
836 let digits = digits.cast();
837 let count_ptr = count.as_mut_ptr();
838 let (order, endian) = (order.order(), order.endian());
839 let raw = self.as_raw();
840 unsafe {
841 gmp::mpz_export(
842 digits,
843 count_ptr,
844 order,
845 T::PRIVATE.bytes,
846 endian,
847 T::PRIVATE.nails,
848 raw,
849 );
850 }
851 assert_eq!(unsafe { count.assume_init() }, digit_count);
852 }
853
854 /// Extracts a [slice] of [limbs][limb_t] used to store the value.
855 ///
856 /// The [slice] contains the absolute value of `self`, with the least
857 /// significant limb first.
858 ///
859 /// The [`Integer`] type also implements
860 /// <code>[AsRef]\<[\[][slice][limb_t][][\]][slice]></code>, which is
861 /// equivalent to this method.
862 ///
863 /// # Examples
864 ///
865 /// ```rust
866 /// use rug::Integer;
867 /// assert!(Integer::new().as_limbs().is_empty());
868 /// assert_eq!(Integer::from(13).as_limbs(), &[13]);
869 /// assert_eq!(Integer::from(-23).as_limbs(), &[23]);
870 /// ```
871 ///
872 /// `int.as_limbs()` is like a borrowing non-copy version of
873 /// <code>int.[to\_digits][Integer::to_digits]::\<[limb\_t]>([Order]::[Lsf][Order::Lsf])</code>.
874 ///
875 /// ```rust
876 /// use gmp_mpfr_sys::gmp::limb_t;
877 /// use rug::integer::Order;
878 /// use rug::Integer;
879 /// let int = Integer::from(0x1234_5678_9abc_def0u64);
880 /// // no copying for int_slice, which is borrowing int
881 /// let int_slice = int.as_limbs();
882 /// // digits is a copy and does not borrow int
883 /// let digits = int.to_digits::<limb_t>(Order::Lsf);
884 /// // no copying for digits_slice, which is borrowing digits
885 /// let digits_slice = &digits[..];
886 /// assert_eq!(int_slice, digits_slice);
887 /// ```
888 ///
889 /// [slice]: prim@slice
890 pub const fn as_limbs(&self) -> &[limb_t] {
891 self.inner_data()
892 }
893
894 /// Creates an [`Integer`] from an [`f32`] if it is
895 /// [finite][f32::is_finite], rounding towards zero.
896 ///
897 /// This conversion can also be performed using
898 /// <code>value.[checked\_as]::\<[Integer]>()</code>.
899 ///
900 /// # Examples
901 ///
902 /// ```rust
903 /// use rug::Integer;
904 /// let i = Integer::from_f32(-5.6).unwrap();
905 /// assert_eq!(i, -5);
906 /// let neg_inf = Integer::from_f32(f32::NEG_INFINITY);
907 /// assert!(neg_inf.is_none());
908 /// ```
909 ///
910 /// [checked\_as]: az::CheckedAs::checked_as
911 #[inline]
912 pub fn from_f32(value: f32) -> Option<Self> {
913 value.checked_cast()
914 }
915
916 /// Creates an [`Integer`] from an [`f64`] if it is
917 /// [finite][f64::is_finite], rounding towards zero.
918 ///
919 /// This conversion can also be performed using
920 /// <code>value.[checked\_as]::\<[Integer]>()</code>.
921 ///
922 /// # Examples
923 ///
924 /// ```rust
925 /// use rug::Integer;
926 /// let i = Integer::from_f64(1e20).unwrap();
927 /// assert_eq!(i, "100000000000000000000".parse::<Integer>().unwrap());
928 /// let inf = Integer::from_f64(f64::INFINITY);
929 /// assert!(inf.is_none());
930 /// ```
931 ///
932 /// [checked\_as]: az::CheckedAs::checked_as
933 #[inline]
934 pub fn from_f64(value: f64) -> Option<Self> {
935 value.checked_cast()
936 }
937
938 /// Parses an [`Integer`] using the given radix.
939 ///
940 /// # Panics
941 ///
942 /// Panics if `radix` is less than 2 or greater than 36.
943 ///
944 /// # Examples
945 ///
946 /// ```rust
947 /// use rug::Integer;
948 /// let i = Integer::from_str_radix("-ff", 16).unwrap();
949 /// assert_eq!(i, -0xff);
950 /// ```
951 #[inline]
952 pub fn from_str_radix(src: &str, radix: i32) -> Result<Self, ParseIntegerError> {
953 Ok(Integer::from(Integer::parse_radix(src, radix)?))
954 }
955
956 /// Parses a decimal string slice (<code>\&[str]</code>) or byte slice
957 /// (<code>[\&\[][slice][u8][][\]][slice]</code>) into an [`Integer`].
958 ///
959 /// The following are implemented with the unwrapped returned
960 /// [incomplete-computation value][icv] as `Src`:
961 /// * <code>[Assign]\<Src> for [Integer]</code>
962 /// * <code>[From]\<Src> for [Integer]</code>
963 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
964 ///
965 /// The string can start with an optional minus or plus sign. ASCII
966 /// whitespace is ignored everywhere in the string. Underscores anywhere
967 /// except before the first digit are ignored as well.
968 ///
969 /// # Examples
970 ///
971 /// ```rust
972 /// use rug::{Complete, Integer};
973 ///
974 /// assert_eq!(Integer::parse("1223").unwrap().complete(), 1223);
975 /// assert_eq!(Integer::parse("123 456 789").unwrap().complete(), 123_456_789);
976 ///
977 /// let invalid = Integer::parse("789a");
978 /// assert!(invalid.is_err());
979 /// ```
980 ///
981 /// [icv]: crate#incomplete-computation-values
982 /// [slice]: prim@slice
983 #[inline]
984 pub fn parse<S: AsRef<[u8]>>(src: S) -> Result<ParseIncomplete, ParseIntegerError> {
985 parse(src.as_ref(), 10)
986 }
987
988 /// Parses a string slice (<code>\&[str]</code>) or byte slice
989 /// (<code>[\&\[][slice][u8][][\]][slice]</code>) into an
990 /// [`Integer`].
991 ///
992 /// The following are implemented with the unwrapped returned
993 /// [incomplete-computation value][icv] as `Src`:
994 /// * <code>[Assign]\<Src> for [Integer]</code>
995 /// * <code>[From]\<Src> for [Integer]</code>
996 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
997 ///
998 /// The string can start with an optional minus or plus sign. ASCII
999 /// whitespace is ignored everywhere in the string. Underscores anywhere
1000 /// except before the first digit are ignored as well.
1001 ///
1002 /// See also [`assign_bytes_radix_unchecked`], which is an unsafe low-level
1003 /// method that can be used if parsing is already done by an external
1004 /// function.
1005 ///
1006 /// # Panics
1007 ///
1008 /// Panics if `radix` is less than 2 or greater than 36.
1009 ///
1010 /// # Examples
1011 ///
1012 /// ```rust
1013 /// use rug::{Complete, Integer};
1014 ///
1015 /// let valid1 = Integer::parse_radix("1223", 4);
1016 /// assert_eq!(valid1.unwrap().complete(), 3 + 4 * (2 + 4 * (2 + 4 * 1)));
1017 /// let valid2 = Integer::parse_radix("1234 abcd", 16);
1018 /// assert_eq!(valid2.unwrap().complete(), 0x1234_abcd);
1019 ///
1020 /// let invalid = Integer::parse_radix("123", 3);
1021 /// assert!(invalid.is_err());
1022 /// ```
1023 ///
1024 /// [`assign_bytes_radix_unchecked`]: Self::assign_bytes_radix_unchecked
1025 /// [icv]: crate#incomplete-computation-values
1026 /// [slice]: prim@slice
1027 #[inline]
1028 pub fn parse_radix<S: AsRef<[u8]>>(
1029 src: S,
1030 radix: i32,
1031 ) -> Result<ParseIncomplete, ParseIntegerError> {
1032 parse(src.as_ref(), radix)
1033 }
1034
1035 /// Assigns from bytes in the given radix.
1036 ///
1037 /// The radix must be between 2 and 256 inclusive.
1038 ///
1039 /// Each byte must be a value from 0 to `radix - 1`, not an ASCII character.
1040 /// The bytes must be ordered most-significant byte first.
1041 ///
1042 /// If `is_negative` is [`true`], the returned value is negative (unless it is 0).
1043 ///
1044 /// # Safety
1045 ///
1046 /// The caller must ensure that
1047 ///
1048 /// * 2 ≤ `radix` ≤ 256
1049 /// * all bytes are in the range 0 ≤ <i>x</i> < `radix`
1050 ///
1051 /// # Examples
1052 ///
1053 /// ```rust
1054 /// use rug::Integer;
1055 /// let bytes = &[0, 3, 9, 2];
1056 /// let radix = 10;
1057 /// let neg = true;
1058 /// let mut i = Integer::new();
1059 /// // SAFETY: radix and bytes are in the required ranges
1060 /// unsafe {
1061 /// i.assign_bytes_radix_unchecked(bytes, radix, neg);
1062 /// }
1063 /// assert_eq!(i, -392);
1064 /// ```
1065 pub unsafe fn assign_bytes_radix_unchecked(
1066 &mut self,
1067 bytes: &[u8],
1068 radix: i32,
1069 is_negative: bool,
1070 ) {
1071 if bytes.is_empty() {
1072 xmpz::set_0(self);
1073 return;
1074 }
1075 xmpz::realloc_for_mpn_set_str(self, bytes.len(), radix);
1076 unsafe {
1077 let size = gmp::mpn_set_str(self.inner.d.as_ptr(), bytes.as_ptr(), bytes.len(), radix);
1078 self.inner.size = (if is_negative { -size } else { size }).unwrapped_cast();
1079 }
1080 }
1081
1082 /// Converts to an [`i8`] if the value fits.
1083 ///
1084 /// This conversion can also be performed using
1085 /// * <code>[i8]::[try\_from]\(\&integer)</code>
1086 /// * <code>[i8]::[try\_from]\(integer)</code>
1087 /// * <code>(\&integer).[checked\_as]::\<[i8]>()</code>
1088 /// * <code>integer.[borrow]\().[checked\_as]::\<[i8]>()</code>
1089 /// * <code>integer.[checked\_as]::\<[i8]>()</code>
1090 ///
1091 /// # Examples
1092 ///
1093 /// ```rust
1094 /// use rug::Integer;
1095 /// let fits = Integer::from(-100);
1096 /// assert_eq!(fits.to_i8(), Some(-100));
1097 /// let small = Integer::from(-200);
1098 /// assert_eq!(small.to_i8(), None);
1099 /// let large = Integer::from(200);
1100 /// assert_eq!(large.to_i8(), None);
1101 /// ```
1102 ///
1103 /// [borrow]: core::borrow::Borrow::borrow
1104 /// [checked\_as]: az::CheckedAs::checked_as
1105 /// [try\_from]: core::convert::TryFrom::try_from
1106 #[inline]
1107 pub fn to_i8(&self) -> Option<i8> {
1108 self.checked_cast()
1109 }
1110
1111 /// Converts to an [`i16`] if the value fits.
1112 ///
1113 /// This conversion can also be performed using
1114 /// * <code>[i16]::[try\_from]\(\&integer)</code>
1115 /// * <code>[i16]::[try\_from]\(integer)</code>
1116 /// * <code>(\&integer).[checked\_as]::\<[i16]>()</code>
1117 /// * <code>integer.[borrow]\().[checked\_as]::\<[i16]>()</code>
1118 /// * <code>integer.[checked\_as]::\<[i16]>()</code>
1119 ///
1120 /// # Examples
1121 ///
1122 /// ```rust
1123 /// use rug::Integer;
1124 /// let fits = Integer::from(-30_000);
1125 /// assert_eq!(fits.to_i16(), Some(-30_000));
1126 /// let small = Integer::from(-40_000);
1127 /// assert_eq!(small.to_i16(), None);
1128 /// let large = Integer::from(40_000);
1129 /// assert_eq!(large.to_i16(), None);
1130 /// ```
1131 ///
1132 /// [borrow]: core::borrow::Borrow::borrow
1133 /// [checked\_as]: az::CheckedAs::checked_as
1134 /// [try\_from]: core::convert::TryFrom::try_from
1135 #[inline]
1136 pub fn to_i16(&self) -> Option<i16> {
1137 self.checked_cast()
1138 }
1139
1140 /// Converts to an [`i32`] if the value fits.
1141 ///
1142 /// This conversion can also be performed using
1143 /// * <code>[i32]::[try\_from]\(\&integer)</code>
1144 /// * <code>[i32]::[try\_from]\(integer)</code>
1145 /// * <code>(\&integer).[checked\_as]::\<[i32]>()</code>
1146 /// * <code>integer.[borrow]\().[checked\_as]::\<[i32]>()</code>
1147 /// * <code>integer.[checked\_as]::\<[i32]>()</code>
1148 ///
1149 /// # Examples
1150 ///
1151 /// ```rust
1152 /// use rug::Integer;
1153 /// let fits = Integer::from(-50);
1154 /// assert_eq!(fits.to_i32(), Some(-50));
1155 /// let small = Integer::from(-123456789012345_i64);
1156 /// assert_eq!(small.to_i32(), None);
1157 /// let large = Integer::from(123456789012345_i64);
1158 /// assert_eq!(large.to_i32(), None);
1159 /// ```
1160 ///
1161 /// [borrow]: core::borrow::Borrow::borrow
1162 /// [checked\_as]: az::CheckedAs::checked_as
1163 /// [try\_from]: core::convert::TryFrom::try_from
1164 #[inline]
1165 pub fn to_i32(&self) -> Option<i32> {
1166 self.checked_cast()
1167 }
1168
1169 /// Converts to an [`i64`] if the value fits.
1170 ///
1171 /// This conversion can also be performed using
1172 /// * <code>[i64]::[try\_from]\(\&integer)</code>
1173 /// * <code>[i64]::[try\_from]\(integer)</code>
1174 /// * <code>(\&integer).[checked\_as]::\<[i64]>()</code>
1175 /// * <code>integer.[borrow]\().[checked\_as]::\<[i64]>()</code>
1176 /// * <code>integer.[checked\_as]::\<[i64]>()</code>
1177 ///
1178 /// # Examples
1179 ///
1180 /// ```rust
1181 /// use rug::Integer;
1182 /// let fits = Integer::from(-50);
1183 /// assert_eq!(fits.to_i64(), Some(-50));
1184 /// let small = Integer::from_str_radix("-fedcba9876543210", 16).unwrap();
1185 /// assert_eq!(small.to_i64(), None);
1186 /// let large = Integer::from_str_radix("fedcba9876543210", 16).unwrap();
1187 /// assert_eq!(large.to_i64(), None);
1188 /// ```
1189 ///
1190 /// [borrow]: core::borrow::Borrow::borrow
1191 /// [checked\_as]: az::CheckedAs::checked_as
1192 /// [try\_from]: core::convert::TryFrom::try_from
1193 #[inline]
1194 pub fn to_i64(&self) -> Option<i64> {
1195 self.checked_cast()
1196 }
1197
1198 /// Converts to an [`i128`] if the value fits.
1199 ///
1200 /// This conversion can also be performed using
1201 /// * <code>[i128]::[try\_from]\(\&integer)</code>
1202 /// * <code>[i128]::[try\_from]\(integer)</code>
1203 /// * <code>(\&integer).[checked\_as]::\<[i128]>()</code>
1204 /// * <code>integer.[borrow]\().[checked\_as]::\<[i128]>()</code>
1205 /// * <code>integer.[checked\_as]::\<[i128]>()</code>
1206 ///
1207 /// # Examples
1208 ///
1209 /// ```rust
1210 /// use rug::Integer;
1211 /// let fits = Integer::from(-50);
1212 /// assert_eq!(fits.to_i128(), Some(-50));
1213 /// let small: Integer = Integer::from(-1) << 130;
1214 /// assert_eq!(small.to_i128(), None);
1215 /// let large: Integer = Integer::from(1) << 130;
1216 /// assert_eq!(large.to_i128(), None);
1217 /// ```
1218 ///
1219 /// [borrow]: core::borrow::Borrow::borrow
1220 /// [checked\_as]: az::CheckedAs::checked_as
1221 /// [try\_from]: core::convert::TryFrom::try_from
1222 #[inline]
1223 pub fn to_i128(&self) -> Option<i128> {
1224 self.checked_cast()
1225 }
1226
1227 /// Converts to an [`isize`] if the value fits.
1228 ///
1229 /// This conversion can also be performed using
1230 /// * <code>[isize]::[try\_from]\(\&integer)</code>
1231 /// * <code>[isize]::[try\_from]\(integer)</code>
1232 /// * <code>(\&integer).[checked\_as]::\<[isize]>()</code>
1233 /// * <code>integer.[borrow]\().[checked\_as]::\<[isize]>()</code>
1234 /// * <code>integer.[checked\_as]::\<[isize]>()</code>
1235 ///
1236 /// # Examples
1237 ///
1238 /// ```rust
1239 /// use rug::Integer;
1240 /// let fits = Integer::from(0x1000);
1241 /// assert_eq!(fits.to_isize(), Some(0x1000));
1242 /// let large: Integer = Integer::from(0x1000) << 128;
1243 /// assert_eq!(large.to_isize(), None);
1244 /// ```
1245 ///
1246 /// [borrow]: core::borrow::Borrow::borrow
1247 /// [checked\_as]: az::CheckedAs::checked_as
1248 /// [try\_from]: core::convert::TryFrom::try_from
1249 #[inline]
1250 pub fn to_isize(&self) -> Option<isize> {
1251 self.checked_cast()
1252 }
1253
1254 /// Converts to an [`u8`] if the value fits.
1255 ///
1256 /// This conversion can also be performed using
1257 /// * <code>[u8]::[try\_from]\(\&integer)</code>
1258 /// * <code>[u8]::[try\_from]\(integer)</code>
1259 /// * <code>(\&integer).[checked\_as]::\<[u8]>()</code>
1260 /// * <code>integer.[borrow]\().[checked\_as]::\<[u8]>()</code>
1261 /// * <code>integer.[checked\_as]::\<[u8]>()</code>
1262 ///
1263 /// # Examples
1264 ///
1265 /// ```rust
1266 /// use rug::Integer;
1267 /// let fits = Integer::from(200);
1268 /// assert_eq!(fits.to_u8(), Some(200));
1269 /// let neg = Integer::from(-1);
1270 /// assert_eq!(neg.to_u8(), None);
1271 /// let large = Integer::from(300);
1272 /// assert_eq!(large.to_u8(), None);
1273 /// ```
1274 ///
1275 /// [borrow]: core::borrow::Borrow::borrow
1276 /// [checked\_as]: az::CheckedAs::checked_as
1277 /// [try\_from]: core::convert::TryFrom::try_from
1278 #[inline]
1279 pub fn to_u8(&self) -> Option<u8> {
1280 self.checked_cast()
1281 }
1282
1283 /// Converts to an [`u16`] if the value fits.
1284 ///
1285 /// This conversion can also be performed using
1286 /// * <code>[u16]::[try\_from]\(\&integer)</code>
1287 /// * <code>[u16]::[try\_from]\(integer)</code>
1288 /// * <code>(\&integer).[checked\_as]::\<[u16]>()</code>
1289 /// * <code>integer.[borrow]\().[checked\_as]::\<[u16]>()</code>
1290 /// * <code>integer.[checked\_as]::\<[u16]>()</code>
1291 ///
1292 /// # Examples
1293 ///
1294 /// ```rust
1295 /// use rug::Integer;
1296 /// let fits = Integer::from(60_000);
1297 /// assert_eq!(fits.to_u16(), Some(60_000));
1298 /// let neg = Integer::from(-1);
1299 /// assert_eq!(neg.to_u16(), None);
1300 /// let large = Integer::from(70_000);
1301 /// assert_eq!(large.to_u16(), None);
1302 /// ```
1303 ///
1304 /// [borrow]: core::borrow::Borrow::borrow
1305 /// [checked\_as]: az::CheckedAs::checked_as
1306 /// [try\_from]: core::convert::TryFrom::try_from
1307 #[inline]
1308 pub fn to_u16(&self) -> Option<u16> {
1309 self.checked_cast()
1310 }
1311
1312 /// Converts to an [`u32`] if the value fits.
1313 ///
1314 /// This conversion can also be performed using
1315 /// * <code>[u32]::[try\_from]\(\&integer)</code>
1316 /// * <code>[u32]::[try\_from]\(integer)</code>
1317 /// * <code>(\&integer).[checked\_as]::\<[u32]>()</code>
1318 /// * <code>integer.[borrow]\().[checked\_as]::\<[u32]>()</code>
1319 /// * <code>integer.[checked\_as]::\<[u32]>()</code>
1320 ///
1321 /// # Examples
1322 ///
1323 /// ```rust
1324 /// use rug::Integer;
1325 /// let fits = Integer::from(1234567890);
1326 /// assert_eq!(fits.to_u32(), Some(1234567890));
1327 /// let neg = Integer::from(-1);
1328 /// assert_eq!(neg.to_u32(), None);
1329 /// let large = Integer::from(123456789012345_u64);
1330 /// assert_eq!(large.to_u32(), None);
1331 /// ```
1332 ///
1333 /// [borrow]: core::borrow::Borrow::borrow
1334 /// [checked\_as]: az::CheckedAs::checked_as
1335 /// [try\_from]: core::convert::TryFrom::try_from
1336 #[inline]
1337 pub fn to_u32(&self) -> Option<u32> {
1338 self.checked_cast()
1339 }
1340
1341 /// Converts to an [`u64`] if the value fits.
1342 ///
1343 /// This conversion can also be performed using
1344 /// * <code>[u64]::[try\_from]\(\&integer)</code>
1345 /// * <code>[u64]::[try\_from]\(integer)</code>
1346 /// * <code>(\&integer).[checked\_as]::\<[u64]>()</code>
1347 /// * <code>integer.[borrow]\().[checked\_as]::\<[u64]>()</code>
1348 /// * <code>integer.[checked\_as]::\<[u64]>()</code>
1349 ///
1350 /// # Examples
1351 ///
1352 /// ```rust
1353 /// use rug::Integer;
1354 /// let fits = Integer::from(123456789012345_u64);
1355 /// assert_eq!(fits.to_u64(), Some(123456789012345));
1356 /// let neg = Integer::from(-1);
1357 /// assert_eq!(neg.to_u64(), None);
1358 /// let large = "1234567890123456789012345".parse::<Integer>().unwrap();
1359 /// assert_eq!(large.to_u64(), None);
1360 /// ```
1361 ///
1362 /// [borrow]: core::borrow::Borrow::borrow
1363 /// [checked\_as]: az::CheckedAs::checked_as
1364 /// [try\_from]: core::convert::TryFrom::try_from
1365 #[inline]
1366 pub fn to_u64(&self) -> Option<u64> {
1367 self.checked_cast()
1368 }
1369
1370 /// Converts to an [`u128`] if the value fits.
1371 ///
1372 /// This conversion can also be performed using
1373 /// * <code>[u128]::[try\_from]\(\&integer)</code>
1374 /// * <code>[u128]::[try\_from]\(integer)</code>
1375 /// * <code>(\&integer).[checked\_as]::\<[u128]>()</code>
1376 /// * <code>integer.[borrow]\().[checked\_as]::\<[u128]>()</code>
1377 /// * <code>integer.[checked\_as]::\<[u128]>()</code>
1378 ///
1379 /// # Examples
1380 ///
1381 /// ```rust
1382 /// use rug::Integer;
1383 /// let fits = Integer::from(12345678901234567890_u128);
1384 /// assert_eq!(fits.to_u128(), Some(12345678901234567890));
1385 /// let neg = Integer::from(-1);
1386 /// assert_eq!(neg.to_u128(), None);
1387 /// let large = "1234567890123456789012345678901234567890"
1388 /// .parse::<Integer>()
1389 /// .unwrap();
1390 /// assert_eq!(large.to_u128(), None);
1391 /// ```
1392 ///
1393 /// [borrow]: core::borrow::Borrow::borrow
1394 /// [checked\_as]: az::CheckedAs::checked_as
1395 /// [try\_from]: core::convert::TryFrom::try_from
1396 #[inline]
1397 pub fn to_u128(&self) -> Option<u128> {
1398 self.checked_cast()
1399 }
1400
1401 /// Converts to an [`usize`] if the value fits.
1402 ///
1403 /// This conversion can also be performed using
1404 /// * <code>[usize]::[try\_from]\(\&integer)</code>
1405 /// * <code>[usize]::[try\_from]\(integer)</code>
1406 /// * <code>(\&integer).[checked\_as]::\<[usize]>()</code>
1407 /// * <code>integer.[borrow]\().[checked\_as]::\<[usize]>()</code>
1408 /// * <code>integer.[checked\_as]::\<[usize]>()</code>
1409 ///
1410 /// # Examples
1411 ///
1412 /// ```rust
1413 /// use rug::Integer;
1414 /// let fits = Integer::from(0x1000);
1415 /// assert_eq!(fits.to_usize(), Some(0x1000));
1416 /// let neg = Integer::from(-1);
1417 /// assert_eq!(neg.to_usize(), None);
1418 /// let large: Integer = Integer::from(0x1000) << 128;
1419 /// assert_eq!(large.to_usize(), None);
1420 /// ```
1421 ///
1422 /// [borrow]: core::borrow::Borrow::borrow
1423 /// [checked\_as]: az::CheckedAs::checked_as
1424 /// [try\_from]: core::convert::TryFrom::try_from
1425 #[inline]
1426 pub fn to_usize(&self) -> Option<usize> {
1427 self.checked_cast()
1428 }
1429
1430 /// Converts to an [`i8`], wrapping if the value does not fit.
1431 ///
1432 /// This conversion can also be performed using
1433 /// * <code>(\&integer).[wrapping\_as]::\<[i8]>()</code>
1434 /// * <code>integer.[borrow]\().[wrapping\_as]::\<[i8]>()</code>
1435 /// * <code>integer.[wrapping\_as]::\<[i8]>()</code>
1436 ///
1437 /// # Examples
1438 ///
1439 /// ```rust
1440 /// use rug::Integer;
1441 /// let large = Integer::from(0x1234);
1442 /// assert_eq!(large.to_i8_wrapping(), 0x34);
1443 /// ```
1444 ///
1445 /// [borrow]: core::borrow::Borrow::borrow
1446 /// [wrapping\_as]: az::WrappingAs::wrapping_as
1447 #[inline]
1448 pub fn to_i8_wrapping(&self) -> i8 {
1449 self.wrapping_cast()
1450 }
1451
1452 /// Converts to an [`i16`], wrapping if the value does not fit.
1453 ///
1454 /// This conversion can also be performed using
1455 /// * <code>(\&integer).[wrapping\_as]::\<[i16]>()</code>
1456 /// * <code>integer.[borrow]\().[wrapping\_as]::\<[i16]>()</code>
1457 /// * <code>integer.[wrapping\_as]::\<[i16]>()</code>
1458 ///
1459 /// # Examples
1460 ///
1461 /// ```rust
1462 /// use rug::Integer;
1463 /// let large = Integer::from(0x1234_5678);
1464 /// assert_eq!(large.to_i16_wrapping(), 0x5678);
1465 /// ```
1466 ///
1467 /// [borrow]: core::borrow::Borrow::borrow
1468 /// [wrapping\_as]: az::WrappingAs::wrapping_as
1469 #[inline]
1470 pub fn to_i16_wrapping(&self) -> i16 {
1471 self.wrapping_cast()
1472 }
1473
1474 /// Converts to an [`i32`], wrapping if the value does not fit.
1475 ///
1476 /// This conversion can also be performed using
1477 /// * <code>(\&integer).[wrapping\_as]::\<[i32]>()</code>
1478 /// * <code>integer.[borrow]\().[wrapping\_as]::\<[i32]>()</code>
1479 /// * <code>integer.[wrapping\_as]::\<[i32]>()</code>
1480 ///
1481 /// # Examples
1482 ///
1483 /// ```rust
1484 /// use rug::Integer;
1485 /// let large = Integer::from(0x1234_5678_9abc_def0_u64);
1486 /// assert_eq!(large.to_i32_wrapping(), 0x9abc_def0_u32 as i32);
1487 /// ```
1488 ///
1489 /// [borrow]: core::borrow::Borrow::borrow
1490 /// [wrapping\_as]: az::WrappingAs::wrapping_as
1491 #[inline]
1492 pub fn to_i32_wrapping(&self) -> i32 {
1493 self.wrapping_cast()
1494 }
1495
1496 /// Converts to an [`i64`], wrapping if the value does not fit.
1497 ///
1498 /// This conversion can also be performed using
1499 /// * <code>(\&integer).[wrapping\_as]::\<[i64]>()</code>
1500 /// * <code>integer.[borrow]\().[wrapping\_as]::\<[i64]>()</code>
1501 /// * <code>integer.[wrapping\_as]::\<[i64]>()</code>
1502 ///
1503 /// # Examples
1504 ///
1505 /// ```rust
1506 /// use rug::Integer;
1507 /// let large = Integer::from_str_radix("f123456789abcdef0", 16).unwrap();
1508 /// assert_eq!(large.to_i64_wrapping(), 0x1234_5678_9abc_def0);
1509 /// ```
1510 ///
1511 /// [borrow]: core::borrow::Borrow::borrow
1512 /// [wrapping\_as]: az::WrappingAs::wrapping_as
1513 #[inline]
1514 pub fn to_i64_wrapping(&self) -> i64 {
1515 self.wrapping_cast()
1516 }
1517
1518 /// Converts to an [`i128`], wrapping if the value does not fit.
1519 ///
1520 /// This conversion can also be performed using
1521 /// * <code>(\&integer).[wrapping\_as]::\<[i128]>()</code>
1522 /// * <code>integer.[borrow]\().[wrapping\_as]::\<[i128]>()</code>
1523 /// * <code>integer.[wrapping\_as]::\<[i128]>()</code>
1524 ///
1525 /// # Examples
1526 ///
1527 /// ```rust
1528 /// use rug::Integer;
1529 /// let s = "f123456789abcdef0123456789abcdef0";
1530 /// let large = Integer::from_str_radix(s, 16).unwrap();
1531 /// assert_eq!(
1532 /// large.to_i128_wrapping(),
1533 /// 0x1234_5678_9abc_def0_1234_5678_9abc_def0
1534 /// );
1535 /// ```
1536 ///
1537 /// [borrow]: core::borrow::Borrow::borrow
1538 /// [wrapping\_as]: az::WrappingAs::wrapping_as
1539 #[inline]
1540 pub fn to_i128_wrapping(&self) -> i128 {
1541 self.wrapping_cast()
1542 }
1543
1544 /// Converts to an [`isize`], wrapping if the value does not fit.
1545 ///
1546 /// This conversion can also be performed using
1547 /// * <code>(\&integer).[wrapping\_as]::\<[isize]>()</code>
1548 /// * <code>integer.[borrow]\().[wrapping\_as]::\<[isize]>()</code>
1549 /// * <code>integer.[wrapping\_as]::\<[isize]>()</code>
1550 ///
1551 /// # Examples
1552 ///
1553 /// ```rust
1554 /// use rug::Integer;
1555 /// let large: Integer = (Integer::from(0x1000) << 128) | 0x1234;
1556 /// assert_eq!(large.to_isize_wrapping(), 0x1234);
1557 /// ```
1558 ///
1559 /// [borrow]: core::borrow::Borrow::borrow
1560 /// [wrapping\_as]: az::WrappingAs::wrapping_as
1561 #[inline]
1562 pub fn to_isize_wrapping(&self) -> isize {
1563 self.wrapping_cast()
1564 }
1565
1566 /// Converts to a [`u8`], wrapping if the value does not fit.
1567 ///
1568 /// This conversion can also be performed using
1569 /// * <code>(\&integer).[wrapping\_as]::\<[u8]>()</code>
1570 /// * <code>integer.[borrow]\().[wrapping\_as]::\<[u8]>()</code>
1571 /// * <code>integer.[wrapping\_as]::\<[u8]>()</code>
1572 ///
1573 /// # Examples
1574 ///
1575 /// ```rust
1576 /// use rug::Integer;
1577 /// let neg = Integer::from(-1);
1578 /// assert_eq!(neg.to_u8_wrapping(), 0xff);
1579 /// let large = Integer::from(0x1234);
1580 /// assert_eq!(large.to_u8_wrapping(), 0x34);
1581 /// ```
1582 ///
1583 /// [borrow]: core::borrow::Borrow::borrow
1584 /// [wrapping\_as]: az::WrappingAs::wrapping_as
1585 #[inline]
1586 pub fn to_u8_wrapping(&self) -> u8 {
1587 self.wrapping_cast()
1588 }
1589
1590 /// Converts to a [`u16`], wrapping if the value does not fit.
1591 ///
1592 /// This conversion can also be performed using
1593 /// * <code>(\&integer).[wrapping\_as]::\<[u16]>()</code>
1594 /// * <code>integer.[borrow]\().[wrapping\_as]::\<[u16]>()</code>
1595 /// * <code>integer.[wrapping\_as]::\<[u16]>()</code>
1596 ///
1597 /// # Examples
1598 ///
1599 /// ```rust
1600 /// use rug::Integer;
1601 /// let neg = Integer::from(-1);
1602 /// assert_eq!(neg.to_u16_wrapping(), 0xffff);
1603 /// let large = Integer::from(0x1234_5678);
1604 /// assert_eq!(large.to_u16_wrapping(), 0x5678);
1605 /// ```
1606 ///
1607 /// [borrow]: core::borrow::Borrow::borrow
1608 /// [wrapping\_as]: az::WrappingAs::wrapping_as
1609 #[inline]
1610 pub fn to_u16_wrapping(&self) -> u16 {
1611 self.wrapping_cast()
1612 }
1613
1614 /// Converts to a [`u32`], wrapping if the value does not fit.
1615 ///
1616 /// This conversion can also be performed using
1617 /// * <code>(\&integer).[wrapping\_as]::\<[u32]>()</code>
1618 /// * <code>integer.[borrow]\().[wrapping\_as]::\<[u32]>()</code>
1619 /// * <code>integer.[wrapping\_as]::\<[u32]>()</code>
1620 ///
1621 /// # Examples
1622 ///
1623 /// ```rust
1624 /// use rug::Integer;
1625 /// let neg = Integer::from(-1);
1626 /// assert_eq!(neg.to_u32_wrapping(), 0xffff_ffff);
1627 /// let large = Integer::from(0x1234_5678_9abc_def0_u64);
1628 /// assert_eq!(large.to_u32_wrapping(), 0x9abc_def0);
1629 /// ```
1630 ///
1631 /// [borrow]: core::borrow::Borrow::borrow
1632 /// [wrapping\_as]: az::WrappingAs::wrapping_as
1633 #[inline]
1634 pub fn to_u32_wrapping(&self) -> u32 {
1635 self.wrapping_cast()
1636 }
1637
1638 /// Converts to a [`u64`], wrapping if the value does not fit.
1639 ///
1640 /// This conversion can also be performed using
1641 /// * <code>(\&integer).[wrapping\_as]::\<[u64]>()</code>
1642 /// * <code>integer.[borrow]\().[wrapping\_as]::\<[u64]>()</code>
1643 /// * <code>integer.[wrapping\_as]::\<[u64]>()</code>
1644 ///
1645 /// # Examples
1646 ///
1647 /// ```rust
1648 /// use rug::Integer;
1649 /// let neg = Integer::from(-1);
1650 /// assert_eq!(neg.to_u64_wrapping(), 0xffff_ffff_ffff_ffff);
1651 /// let large = Integer::from_str_radix("f123456789abcdef0", 16).unwrap();
1652 /// assert_eq!(large.to_u64_wrapping(), 0x1234_5678_9abc_def0);
1653 /// ```
1654 ///
1655 /// [borrow]: core::borrow::Borrow::borrow
1656 /// [wrapping\_as]: az::WrappingAs::wrapping_as
1657 #[inline]
1658 pub fn to_u64_wrapping(&self) -> u64 {
1659 self.wrapping_cast()
1660 }
1661
1662 /// Converts to a [`u128`], wrapping if the value does not fit.
1663 ///
1664 /// This conversion can also be performed using
1665 /// * <code>(\&integer).[wrapping\_as]::\<[u128]>()</code>
1666 /// * <code>integer.[borrow]\().[wrapping\_as]::\<[u128]>()</code>
1667 /// * <code>integer.[wrapping\_as]::\<[u128]>()</code>
1668 ///
1669 /// # Examples
1670 ///
1671 /// ```rust
1672 /// use rug::Integer;
1673 /// let neg = Integer::from(-1);
1674 /// assert_eq!(
1675 /// neg.to_u128_wrapping(),
1676 /// 0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff
1677 /// );
1678 /// let s = "f123456789abcdef0123456789abcdef0";
1679 /// let large = Integer::from_str_radix(s, 16).unwrap();
1680 /// assert_eq!(
1681 /// large.to_u128_wrapping(),
1682 /// 0x1234_5678_9abc_def0_1234_5678_9abc_def0
1683 /// );
1684 /// ```
1685 ///
1686 /// [borrow]: core::borrow::Borrow::borrow
1687 /// [wrapping\_as]: az::WrappingAs::wrapping_as
1688 #[inline]
1689 pub fn to_u128_wrapping(&self) -> u128 {
1690 self.wrapping_cast()
1691 }
1692
1693 /// Converts to a [`usize`], wrapping if the value does not fit.
1694 ///
1695 /// This conversion can also be performed using
1696 /// * <code>(\&integer).[wrapping\_as]::\<[usize]>()</code>
1697 /// * <code>integer.[borrow]\().[wrapping\_as]::\<[usize]>()</code>
1698 /// * <code>integer.[wrapping\_as]::\<[usize]>()</code>
1699 ///
1700 /// # Examples
1701 ///
1702 /// ```rust
1703 /// use rug::Integer;
1704 /// let large: Integer = (Integer::from(0x1000) << 128) | 0x1234;
1705 /// assert_eq!(large.to_usize_wrapping(), 0x1234);
1706 /// ```
1707 ///
1708 /// [borrow]: core::borrow::Borrow::borrow
1709 /// [wrapping\_as]: az::WrappingAs::wrapping_as
1710 #[inline]
1711 pub fn to_usize_wrapping(&self) -> usize {
1712 self.wrapping_cast()
1713 }
1714
1715 /// Converts to an [`f32`], rounding towards zero.
1716 ///
1717 /// This conversion can also be performed using
1718 /// * <code>(\&integer).[az]::\<[f32]>()</code>
1719 /// * <code>integer.[borrow]\().[az]::\<[f32]>()</code>
1720 /// * <code>integer.[az]::\<[f32]>()</code>
1721 ///
1722 /// # Examples
1723 ///
1724 /// ```rust
1725 /// use rug::Integer;
1726 /// let min = Integer::from_f32(f32::MIN).unwrap();
1727 /// let min_minus_one = min - 1u32;
1728 /// // min_minus_one is truncated to f32::MIN
1729 /// assert_eq!(min_minus_one.to_f32(), f32::MIN);
1730 /// let times_two = min_minus_one * 2u32;
1731 /// // times_two is too small
1732 /// assert_eq!(times_two.to_f32(), f32::NEG_INFINITY);
1733 /// ```
1734 ///
1735 /// [az]: az::Az::az
1736 /// [borrow]: core::borrow::Borrow::borrow
1737 #[inline]
1738 pub fn to_f32(&self) -> f32 {
1739 self.cast()
1740 }
1741
1742 /// Converts to an [`f64`], rounding towards zero.
1743 ///
1744 /// This conversion can also be performed using
1745 /// * <code>(\&integer).[az]::\<[f64]>()</code>
1746 /// * <code>integer.[borrow]\().[az]::\<[f64]>()</code>
1747 /// * <code>integer.[az]::\<[f64]>()</code>
1748 ///
1749 /// # Examples
1750 ///
1751 /// ```rust
1752 /// use rug::Integer;
1753 ///
1754 /// // An `f64` has 53 bits of precision.
1755 /// let exact = 0x1f_ffff_ffff_ffff_u64;
1756 /// let i = Integer::from(exact);
1757 /// assert_eq!(i.to_f64(), exact as f64);
1758 ///
1759 /// // large has 56 ones
1760 /// let large = 0xff_ffff_ffff_ffff_u64;
1761 /// // trunc has 53 ones followed by 3 zeros
1762 /// let trunc = 0xff_ffff_ffff_fff8_u64;
1763 /// let j = Integer::from(large);
1764 /// assert_eq!(j.to_f64() as u64, trunc);
1765 ///
1766 /// let max = Integer::from_f64(f64::MAX).unwrap();
1767 /// let max_plus_one = max + 1u32;
1768 /// // max_plus_one is truncated to f64::MAX
1769 /// assert_eq!(max_plus_one.to_f64(), f64::MAX);
1770 /// let times_two = max_plus_one * 2u32;
1771 /// // times_two is too large
1772 /// assert_eq!(times_two.to_f64(), f64::INFINITY);
1773 /// ```
1774 ///
1775 /// [az]: az::Az::az
1776 /// [borrow]: core::borrow::Borrow::borrow
1777 #[inline]
1778 pub fn to_f64(&self) -> f64 {
1779 self.cast()
1780 }
1781
1782 /// Converts to an [`f32`] and an exponent, rounding towards zero.
1783 ///
1784 /// The returned [`f32`] is in the range
1785 /// 0.5 ≤ <i>x</i> < 1. If the value is zero, `(0.0, 0)`
1786 /// is returned.
1787 ///
1788 /// # Examples
1789 ///
1790 /// ```rust
1791 /// use rug::Integer;
1792 /// let zero = Integer::new();
1793 /// let (d0, exp0) = zero.to_f32_exp();
1794 /// assert_eq!((d0, exp0), (0.0, 0));
1795 /// let fifteen = Integer::from(15);
1796 /// let (d15, exp15) = fifteen.to_f32_exp();
1797 /// assert_eq!((d15, exp15), (15.0 / 16.0, 4));
1798 /// ```
1799 #[inline]
1800 pub fn to_f32_exp(&self) -> (f32, u32) {
1801 let (f, exp) = self.to_f64_exp();
1802 let trunc_f = misc::trunc_f64_to_f32(f);
1803 (trunc_f, exp)
1804 }
1805
1806 /// Converts to an [`f64`] and an exponent, rounding towards zero.
1807 ///
1808 /// The returned [`f64`] is in the range
1809 /// 0.5 ≤ <i>x</i> < 1. If the value is zero, `(0.0, 0)`
1810 /// is returned.
1811 ///
1812 /// # Examples
1813 ///
1814 /// ```rust
1815 /// use rug::Integer;
1816 /// let zero = Integer::new();
1817 /// let (d0, exp0) = zero.to_f64_exp();
1818 /// assert_eq!((d0, exp0), (0.0, 0));
1819 /// let fifteen = Integer::from(15);
1820 /// let (d15, exp15) = fifteen.to_f64_exp();
1821 /// assert_eq!((d15, exp15), (15.0 / 16.0, 4));
1822 /// ```
1823 #[inline]
1824 pub fn to_f64_exp(&self) -> (f64, u32) {
1825 let (f, exp) = xmpz::get_f64_2exp(self);
1826 (f, exp.unwrapped_cast())
1827 }
1828
1829 /// Returns a string representation of the number for the specified `radix`.
1830 ///
1831 /// # Panics
1832 ///
1833 /// Panics if `radix` is less than 2 or greater than 36.
1834 ///
1835 /// # Examples
1836 ///
1837 /// ```rust
1838 /// use rug::{Assign, Integer};
1839 /// let mut i = Integer::new();
1840 /// assert_eq!(i.to_string_radix(10), "0");
1841 /// i.assign(-10);
1842 /// assert_eq!(i.to_string_radix(16), "-a");
1843 /// i.assign(0x1234cdef);
1844 /// assert_eq!(i.to_string_radix(4), "102031030313233");
1845 /// i.assign(Integer::parse_radix("123456789aAbBcCdDeEfF", 16).unwrap());
1846 /// assert_eq!(i.to_string_radix(16), "123456789aabbccddeeff");
1847 /// ```
1848 #[cfg(feature = "std")]
1849 #[inline]
1850 pub fn to_string_radix(&self, radix: i32) -> String {
1851 let mut s = StringLike::new_string();
1852 append_to_string(&mut s, self, radix, false);
1853 s.unwrap_string()
1854 }
1855
1856 /// Assigns from an [`f32`] if it is [finite][f32::is_finite], rounding
1857 /// towards zero.
1858 ///
1859 /// # Examples
1860 ///
1861 /// ```rust
1862 /// use rug::Integer;
1863 /// let mut i = Integer::new();
1864 /// let ret = i.assign_f64(-12.7);
1865 /// assert!(ret.is_ok());
1866 /// assert_eq!(i, -12);
1867 /// let ret = i.assign_f32(f32::NAN);
1868 /// assert!(ret.is_err());
1869 /// assert_eq!(i, -12);
1870 /// ```
1871 #[inline]
1872 #[allow(clippy::result_unit_err)]
1873 pub fn assign_f32(&mut self, val: f32) -> Result<(), ()> {
1874 self.assign_f64(val.into())
1875 }
1876
1877 /// Assigns from an [`f64`] if it is [finite][f64::is_finite],
1878 /// rounding towards zero.
1879 ///
1880 /// # Examples
1881 ///
1882 /// ```rust
1883 /// use rug::Integer;
1884 /// let mut i = Integer::new();
1885 /// let ret = i.assign_f64(12.7);
1886 /// assert!(ret.is_ok());
1887 /// assert_eq!(i, 12);
1888 /// let ret = i.assign_f64(1.0 / 0.0);
1889 /// assert!(ret.is_err());
1890 /// assert_eq!(i, 12);
1891 /// ```
1892 #[inline]
1893 #[allow(clippy::result_unit_err)]
1894 pub fn assign_f64(&mut self, val: f64) -> Result<(), ()> {
1895 xmpz::set_f64(self, val)
1896 }
1897
1898 /// Borrows a negated copy of the [`Integer`].
1899 ///
1900 /// The returned object implements <code>[Deref]\<[Target][Deref::Target] = [Integer]></code>.
1901 ///
1902 /// This method performs a shallow copy and negates it, and negation does
1903 /// not change the allocated data.
1904 ///
1905 /// # Examples
1906 ///
1907 /// ```rust
1908 /// use rug::Integer;
1909 /// let i = Integer::from(42);
1910 /// let neg_i = i.as_neg();
1911 /// assert_eq!(*neg_i, -42);
1912 /// // methods taking &self can be used on the returned object
1913 /// let reneg_i = neg_i.as_neg();
1914 /// assert_eq!(*reneg_i, 42);
1915 /// assert_eq!(*reneg_i, i);
1916 /// ```
1917 ///
1918 /// [Deref::Target]: core::ops::Deref::Target
1919 /// [Deref]: core::ops::Deref
1920 pub const fn as_neg(&self) -> BorrowInteger<'_> {
1921 let mut raw = self.inner;
1922 raw.size = match raw.size.checked_neg() {
1923 Some(s) => s,
1924 None => panic!("overflow"),
1925 };
1926 // Safety: the lifetime of the return type is equal to the lifetime of self.
1927 unsafe { BorrowInteger::from_raw(raw) }
1928 }
1929
1930 /// Borrows an absolute copy of the [`Integer`].
1931 ///
1932 /// The returned object implements <code>[Deref]\<[Target][Deref::Target] = [Integer]></code>.
1933 ///
1934 /// This method performs a shallow copy and possibly negates it, and
1935 /// negation does not change the allocated data.
1936 ///
1937 /// # Examples
1938 ///
1939 /// ```rust
1940 /// use rug::Integer;
1941 /// let i = Integer::from(-42);
1942 /// let abs_i = i.as_abs();
1943 /// assert_eq!(*abs_i, 42);
1944 /// // methods taking &self can be used on the returned object
1945 /// let reabs_i = abs_i.as_abs();
1946 /// assert_eq!(*reabs_i, 42);
1947 /// assert_eq!(*reabs_i, *abs_i);
1948 /// ```
1949 ///
1950 /// [Deref::Target]: core::ops::Deref::Target
1951 /// [Deref]: core::ops::Deref
1952 pub const fn as_abs(&self) -> BorrowInteger<'_> {
1953 let mut raw = self.inner;
1954 raw.size = match raw.size.checked_abs() {
1955 Some(s) => s,
1956 None => panic!("overflow"),
1957 };
1958 // Safety: the lifetime of the return type is equal to the lifetime of self.
1959 unsafe { BorrowInteger::from_raw(raw) }
1960 }
1961
1962 #[cfg(feature = "rational")]
1963 /// Borrows a copy of the [`Integer`] as a [`Rational`][Rational] number.
1964 ///
1965 /// The returned object implements
1966 /// <code>[Deref]\<[Target][Deref::Target] = [Rational]></code>.
1967 ///
1968 /// # Examples
1969 ///
1970 /// ```rust
1971 /// use rug::Integer;
1972 /// let i = Integer::from(4);
1973 /// let r = i.as_rational();
1974 /// assert_eq!(*r, 4);
1975 /// // methods taking &self can be used on the returned object
1976 /// let recip_r = r.as_recip();
1977 /// assert_eq!(*recip_r, 0.25);
1978 /// ```
1979 ///
1980 /// [Deref::Target]: core::ops::Deref::Target
1981 /// [Deref]: core::ops::Deref
1982 /// [Rational]: crate::Rational
1983 pub const fn as_rational(&self) -> BorrowRational<'_> {
1984 const ONE: limb_t = 1;
1985 // use NonNull::new_unchecked because NonNull::from is not usable in const
1986 let raw_rational = mpq_t {
1987 num: self.inner,
1988 den: mpz_t {
1989 alloc: 1,
1990 size: 1,
1991 d: unsafe { NonNull::new_unchecked((&ONE as *const limb_t).cast_mut()) },
1992 },
1993 };
1994 // Safety: the lifetime of the return type is equal to the lifetime of self.
1995 // Safety: the number is in canonical form as the denominator is 1.
1996 unsafe { BorrowRational::from_raw(raw_rational) }
1997 }
1998
1999 /// Returns [`true`] if the number is zero.
2000 ///
2001 /// # Examples
2002 ///
2003 /// ```rust
2004 /// use rug::Integer;
2005 /// assert!(Integer::from(0).is_zero());
2006 /// assert!(!(Integer::from(1).is_zero()));
2007 /// ```
2008 #[inline]
2009 pub const fn is_zero(&self) -> bool {
2010 matches!(self.cmp0(), Ordering::Equal)
2011 }
2012
2013 /// Returns [`true`] if the number is positive and [`false`] if the number
2014 /// is zero or negative.
2015 ///
2016 /// # Examples
2017 ///
2018 /// ```rust
2019 /// use rug::Integer;
2020 /// assert!(Integer::from(10).is_positive());
2021 /// assert!(!(Integer::from(-10).is_positive()));
2022 /// ```
2023 #[inline]
2024 pub const fn is_positive(&self) -> bool {
2025 matches!(self.cmp0(), Ordering::Greater)
2026 }
2027
2028 /// Returns [`true`] if the number is negative and [`false`] if the number
2029 /// is zero or positive.
2030 ///
2031 /// # Examples
2032 ///
2033 /// ```rust
2034 /// use rug::Integer;
2035 /// assert!(Integer::from(-10).is_negative());
2036 /// assert!(!(Integer::from(10).is_negative()));
2037 /// ```
2038 #[inline]
2039 pub const fn is_negative(&self) -> bool {
2040 matches!(self.cmp0(), Ordering::Less)
2041 }
2042
2043 /// Returns [`true`] if the number is even.
2044 ///
2045 /// # Examples
2046 ///
2047 /// ```rust
2048 /// use rug::Integer;
2049 /// assert!(!(Integer::from(13).is_even()));
2050 /// assert!(Integer::from(-14).is_even());
2051 /// ```
2052 #[inline]
2053 pub const fn is_even(&self) -> bool {
2054 xmpz::even_p(self)
2055 }
2056
2057 /// Returns [`true`] if the number is odd.
2058 ///
2059 /// # Examples
2060 ///
2061 /// ```rust
2062 /// use rug::Integer;
2063 /// assert!(Integer::from(13).is_odd());
2064 /// assert!(!Integer::from(-14).is_odd());
2065 /// ```
2066 #[inline]
2067 pub const fn is_odd(&self) -> bool {
2068 xmpz::odd_p(self)
2069 }
2070
2071 /// Returns [`true`] if the number is divisible by `divisor`. Unlike other
2072 /// division functions, `divisor` can be zero.
2073 ///
2074 /// # Examples
2075 ///
2076 /// ```rust
2077 /// use rug::Integer;
2078 /// let i = Integer::from(230);
2079 /// assert!(i.is_divisible(&Integer::from(10)));
2080 /// assert!(!i.is_divisible(&Integer::from(100)));
2081 /// assert!(!i.is_divisible(&Integer::new()));
2082 /// ```
2083 #[inline]
2084 pub fn is_divisible(&self, divisor: &Self) -> bool {
2085 xmpz::divisible_p(self, divisor)
2086 }
2087
2088 /// Returns [`true`] if the number is divisible by `divisor`. Unlike other
2089 /// division functions, `divisor` can be zero.
2090 ///
2091 /// # Examples
2092 ///
2093 /// ```rust
2094 /// use rug::Integer;
2095 /// let i = Integer::from(230);
2096 /// assert!(i.is_divisible_u(23));
2097 /// assert!(!i.is_divisible_u(100));
2098 /// assert!(!i.is_divisible_u(0));
2099 /// ```
2100 #[inline]
2101 pub fn is_divisible_u(&self, divisor: u32) -> bool {
2102 xmpz::divisible_ui_p(self, divisor.into())
2103 }
2104
2105 /// Returns [`true`] if the number is divisible by 2<sup><i>b</i></sup>.
2106 ///
2107 /// # Examples
2108 ///
2109 /// ```rust
2110 /// use rug::Integer;
2111 /// let i = Integer::from(15 << 17);
2112 /// assert!(i.is_divisible_2pow(16));
2113 /// assert!(i.is_divisible_2pow(17));
2114 /// assert!(!i.is_divisible_2pow(18));
2115 /// ```
2116 #[inline]
2117 pub fn is_divisible_2pow(&self, b: u32) -> bool {
2118 xmpz::divisible_2exp_p(self, b.into())
2119 }
2120
2121 /// Returns [`true`] if the number is congruent to <i>c</i> mod
2122 /// <i>divisor</i>, that is, if there exists a <i>q</i> such that `self` =
2123 /// <i>c</i> + <i>q</i> × <i>divisor</i>. Unlike other division functions,
2124 /// `divisor` can be zero.
2125 ///
2126 /// # Examples
2127 ///
2128 /// ```rust
2129 /// use rug::Integer;
2130 /// let n = Integer::from(105);
2131 /// let divisor = Integer::from(10);
2132 /// assert!(n.is_congruent(&Integer::from(5), &divisor));
2133 /// assert!(n.is_congruent(&Integer::from(25), &divisor));
2134 /// assert!(!n.is_congruent(&Integer::from(7), &divisor));
2135 /// // n is congruent to itself if divisor is 0
2136 /// assert!(n.is_congruent(&n, &Integer::from(0)));
2137 /// ```
2138 #[inline]
2139 pub fn is_congruent(&self, c: &Self, divisor: &Self) -> bool {
2140 xmpz::congruent_p(self, c, divisor)
2141 }
2142
2143 /// Returns [`true`] if the number is congruent to <i>c</i> mod
2144 /// <i>divisor</i>, that is, if there exists a <i>q</i> such that `self` =
2145 /// <i>c</i> + <i>q</i> × <i>divisor</i>. Unlike other division functions,
2146 /// `divisor` can be zero.
2147 ///
2148 /// # Examples
2149 ///
2150 /// ```rust
2151 /// use rug::Integer;
2152 /// let n = Integer::from(105);
2153 /// assert!(n.is_congruent_u(3335, 10));
2154 /// assert!(!n.is_congruent_u(107, 10));
2155 /// // n is congruent to itself if divisor is 0
2156 /// assert!(n.is_congruent_u(105, 0));
2157 /// ```
2158 #[inline]
2159 pub fn is_congruent_u(&self, c: u32, divisor: u32) -> bool {
2160 xmpz::congruent_ui_p(self, c.into(), divisor.into())
2161 }
2162
2163 /// Returns [`true`] if the number is congruent to <i>c</i> mod
2164 /// 2<sup><i>b</i></sup>, that is, if there exists a <i>q</i> such that
2165 /// `self` = <i>c</i> + <i>q</i> × 2<sup><i>b</i></sup>.
2166 ///
2167 /// # Examples
2168 ///
2169 /// ```rust
2170 /// use rug::Integer;
2171 /// let n = Integer::from(13 << 17 | 21);
2172 /// assert!(n.is_congruent_2pow(&Integer::from(7 << 17 | 21), 17));
2173 /// assert!(!n.is_congruent_2pow(&Integer::from(13 << 17 | 22), 17));
2174 /// ```
2175 #[inline]
2176 pub fn is_congruent_2pow(&self, c: &Self, b: u32) -> bool {
2177 xmpz::congruent_2exp_p(self, c, b.into())
2178 }
2179
2180 /// Returns [`true`] if the number is a perfect power.
2181 ///
2182 /// # Examples
2183 ///
2184 /// ```rust
2185 /// use rug::Integer;
2186 /// // 0 is 0 to the power of anything
2187 /// assert!(Integer::from(0).is_perfect_power());
2188 /// // 25 is 5 to the power of 2
2189 /// assert!(Integer::from(25).is_perfect_power());
2190 /// // -243 is -3 to the power of 5
2191 /// assert!(Integer::from(243).is_perfect_power());
2192 ///
2193 /// assert!(!Integer::from(24).is_perfect_power());
2194 /// assert!(!Integer::from(-100).is_perfect_power());
2195 /// ```
2196 #[inline]
2197 pub fn is_perfect_power(&self) -> bool {
2198 xmpz::perfect_power_p(self)
2199 }
2200
2201 /// Returns [`true`] if the number is a perfect square.
2202 ///
2203 /// # Examples
2204 ///
2205 /// ```rust
2206 /// use rug::Integer;
2207 /// assert!(Integer::from(0).is_perfect_square());
2208 /// assert!(Integer::from(1).is_perfect_square());
2209 /// assert!(Integer::from(4).is_perfect_square());
2210 /// assert!(Integer::from(9).is_perfect_square());
2211 ///
2212 /// assert!(!Integer::from(15).is_perfect_square());
2213 /// assert!(!Integer::from(-9).is_perfect_square());
2214 /// ```
2215 #[inline]
2216 pub fn is_perfect_square(&self) -> bool {
2217 xmpz::perfect_square_p(self)
2218 }
2219
2220 /// Returns [`true`] if the number is a power of two.
2221 ///
2222 /// # Examples
2223 ///
2224 /// ```rust
2225 /// use rug::Integer;
2226 /// assert!(Integer::from(1).is_power_of_two());
2227 /// assert!(Integer::from(4).is_power_of_two());
2228 /// assert!(Integer::from(1 << 30).is_power_of_two());
2229 ///
2230 /// assert!(!Integer::from(7).is_power_of_two());
2231 /// assert!(!Integer::from(0).is_power_of_two());
2232 /// assert!(!Integer::from(-1).is_power_of_two());
2233 /// ```
2234 #[inline]
2235 pub fn is_power_of_two(&self) -> bool {
2236 xmpz::power_of_two_p(self)
2237 }
2238
2239 /// Returns the same result as
2240 /// <code>self.[cmp][Ord::cmp]\(\&0.[into][Into::into]\())</code>, but is
2241 /// faster.
2242 ///
2243 /// # Examples
2244 ///
2245 /// ```rust
2246 /// use core::cmp::Ordering;
2247 /// use rug::Integer;
2248 /// assert_eq!(Integer::from(-5).cmp0(), Ordering::Less);
2249 /// assert_eq!(Integer::from(0).cmp0(), Ordering::Equal);
2250 /// assert_eq!(Integer::from(5).cmp0(), Ordering::Greater);
2251 /// ```
2252 #[inline]
2253 pub const fn cmp0(&self) -> Ordering {
2254 xmpz::sgn(self)
2255 }
2256
2257 /// Compares the absolute values.
2258 ///
2259 /// # Examples
2260 ///
2261 /// ```rust
2262 /// use core::cmp::Ordering;
2263 /// use rug::Integer;
2264 /// let a = Integer::from(-10);
2265 /// let b = Integer::from(4);
2266 /// assert_eq!(a.cmp(&b), Ordering::Less);
2267 /// assert_eq!(a.cmp_abs(&b), Ordering::Greater);
2268 /// ```
2269 #[inline]
2270 pub fn cmp_abs(&self, other: &Self) -> Ordering {
2271 xmpz::cmpabs(self, other)
2272 }
2273
2274 /// Returns the number of bits required to represent the absolute value.
2275 ///
2276 /// # Examples
2277 ///
2278 /// ```rust
2279 /// use rug::Integer;
2280 ///
2281 /// assert_eq!(Integer::from(0).significant_bits(), 0); // “”
2282 /// assert_eq!(Integer::from(1).significant_bits(), 1); // “1”
2283 /// assert_eq!(Integer::from(4).significant_bits(), 3); // “100”
2284 /// assert_eq!(Integer::from(7).significant_bits(), 3); // “111”
2285 /// assert_eq!(Integer::from(-1).significant_bits(), 1); // “1”
2286 /// assert_eq!(Integer::from(-4).significant_bits(), 3); // “100”
2287 /// assert_eq!(Integer::from(-7).significant_bits(), 3); // “111”
2288 /// ```
2289 #[inline]
2290 pub fn significant_bits(&self) -> u32 {
2291 xmpz::significant_bits(self).unwrapped_cast()
2292 }
2293
2294 /// Returns the number of bits required to represent the value using a
2295 /// two’s-complement representation.
2296 ///
2297 /// For non-negative numbers, this method returns one more than
2298 /// the [`significant_bits`] method, since an extra zero is needed
2299 /// before the most significant bit.
2300 ///
2301 /// # Examples
2302 ///
2303 /// ```rust
2304 /// use rug::Integer;
2305 ///
2306 /// assert_eq!(Integer::from(-5).signed_bits(), 4); // “1011”
2307 /// assert_eq!(Integer::from(-4).signed_bits(), 3); // “100”
2308 /// assert_eq!(Integer::from(-3).signed_bits(), 3); // “101”
2309 /// assert_eq!(Integer::from(-2).signed_bits(), 2); // “10”
2310 /// assert_eq!(Integer::from(-1).signed_bits(), 1); // “1”
2311 /// assert_eq!(Integer::from(0).signed_bits(), 1); // “0”
2312 /// assert_eq!(Integer::from(1).signed_bits(), 2); // “01”
2313 /// assert_eq!(Integer::from(2).signed_bits(), 3); // “010”
2314 /// assert_eq!(Integer::from(3).signed_bits(), 3); // “011”
2315 /// assert_eq!(Integer::from(4).signed_bits(), 4); // “0100”
2316 /// ```
2317 ///
2318 /// [`significant_bits`]: Integer::significant_bits
2319 #[inline]
2320 pub fn signed_bits(&self) -> u32 {
2321 xmpz::signed_bits(self).unwrapped_cast()
2322 }
2323
2324 /// Returns the number of one bits if the value ≥ 0.
2325 ///
2326 /// # Examples
2327 ///
2328 /// ```rust
2329 /// use rug::Integer;
2330 /// assert_eq!(Integer::from(0).count_ones(), Some(0));
2331 /// assert_eq!(Integer::from(15).count_ones(), Some(4));
2332 /// assert_eq!(Integer::from(-1).count_ones(), None);
2333 /// ```
2334 #[inline]
2335 pub fn count_ones(&self) -> Option<u32> {
2336 xmpz::popcount(self).map(UnwrappedCast::unwrapped_cast)
2337 }
2338
2339 /// Returns the number of zero bits if the value < 0.
2340 ///
2341 /// # Examples
2342 ///
2343 /// ```rust
2344 /// use rug::Integer;
2345 /// assert_eq!(Integer::from(0).count_zeros(), None);
2346 /// assert_eq!(Integer::from(1).count_zeros(), None);
2347 /// assert_eq!(Integer::from(-1).count_zeros(), Some(0));
2348 /// assert_eq!(Integer::from(-2).count_zeros(), Some(1));
2349 /// assert_eq!(Integer::from(-7).count_zeros(), Some(2));
2350 /// assert_eq!(Integer::from(-8).count_zeros(), Some(3));
2351 /// ```
2352 #[inline]
2353 pub fn count_zeros(&self) -> Option<u32> {
2354 xmpz::zerocount(self).map(UnwrappedCast::unwrapped_cast)
2355 }
2356
2357 /// Returns the location of the first zero, starting at `start`. If the bit
2358 /// at location `start` is zero, returns `start`.
2359 ///
2360 /// # Examples
2361 ///
2362 /// ```rust
2363 /// use rug::Integer;
2364 /// // -2 is ...11111110
2365 /// assert_eq!(Integer::from(-2).find_zero(0), Some(0));
2366 /// assert_eq!(Integer::from(-2).find_zero(1), None);
2367 /// // 15 is ...00001111
2368 /// assert_eq!(Integer::from(15).find_zero(0), Some(4));
2369 /// assert_eq!(Integer::from(15).find_zero(20), Some(20));
2370 /// ```
2371 #[inline]
2372 #[doc(alias = "trailing_ones")]
2373 pub fn find_zero(&self, start: u32) -> Option<u32> {
2374 xmpz::scan0(self, start.into()).map(UnwrappedCast::unwrapped_cast)
2375 }
2376
2377 /// Returns the location of the first one, starting at `start`. If the bit
2378 /// at location `start` is one, returns `start`.
2379 ///
2380 /// # Examples
2381 ///
2382 /// ```rust
2383 /// use rug::Integer;
2384 /// // 1 is ...00000001
2385 /// assert_eq!(Integer::from(1).find_one(0), Some(0));
2386 /// assert_eq!(Integer::from(1).find_one(1), None);
2387 /// // -16 is ...11110000
2388 /// assert_eq!(Integer::from(-16).find_one(0), Some(4));
2389 /// assert_eq!(Integer::from(-16).find_one(20), Some(20));
2390 /// ```
2391 #[inline]
2392 #[doc(alias = "trailing_zeros")]
2393 pub fn find_one(&self, start: u32) -> Option<u32> {
2394 xmpz::scan1(self, start.into()).map(UnwrappedCast::unwrapped_cast)
2395 }
2396
2397 /// Sets the bit at location `index` to 1 if `val` is [`true`] or 0 if `val`
2398 /// is [`false`].
2399 ///
2400 /// # Examples
2401 ///
2402 /// ```rust
2403 /// use rug::{Assign, Integer};
2404 /// let mut i = Integer::from(-1);
2405 /// assert_eq!(*i.set_bit(0, false), -2);
2406 /// i.assign(0xff);
2407 /// assert_eq!(*i.set_bit(11, true), 0x8ff);
2408 /// ```
2409 #[inline]
2410 pub fn set_bit(&mut self, index: u32, val: bool) -> &mut Self {
2411 if val {
2412 xmpz::setbit(self, index.into());
2413 } else {
2414 xmpz::clrbit(self, index.into());
2415 }
2416 self
2417 }
2418
2419 /// Returns [`true`] if the bit at location `index` is 1 or [`false`] if the
2420 /// bit is 0.
2421 ///
2422 /// # Examples
2423 ///
2424 /// ```rust
2425 /// use rug::Integer;
2426 /// let i = Integer::from(0b100101);
2427 /// assert!(i.get_bit(0));
2428 /// assert!(!i.get_bit(1));
2429 /// assert!(i.get_bit(5));
2430 /// let neg = Integer::from(-1);
2431 /// assert!(neg.get_bit(1000));
2432 /// ```
2433 #[inline]
2434 pub fn get_bit(&self, index: u32) -> bool {
2435 xmpz::tstbit(self, index.into())
2436 }
2437
2438 /// Toggles the bit at location `index`.
2439 ///
2440 /// # Examples
2441 ///
2442 /// ```rust
2443 /// use rug::Integer;
2444 /// let mut i = Integer::from(0b100101);
2445 /// i.toggle_bit(5);
2446 /// assert_eq!(i, 0b101);
2447 /// ```
2448 #[inline]
2449 pub fn toggle_bit(&mut self, index: u32) -> &mut Self {
2450 xmpz::combit(self, index.into());
2451 self
2452 }
2453
2454 /// Retuns the Hamming distance if the two numbers have the same sign.
2455 ///
2456 /// The Hamming distance is the number of different bits.
2457 ///
2458 /// # Examples
2459 ///
2460 /// ```rust
2461 /// use rug::Integer;
2462 /// let i = Integer::from(-1);
2463 /// assert_eq!(Integer::from(0).hamming_dist(&i), None);
2464 /// assert_eq!(Integer::from(-1).hamming_dist(&i), Some(0));
2465 /// // -1 is ...11111111 and -13 is ...11110011
2466 /// assert_eq!(Integer::from(-13).hamming_dist(&i), Some(2));
2467 /// ```
2468 #[inline]
2469 pub fn hamming_dist(&self, other: &Self) -> Option<u32> {
2470 xmpz::hamdist(self, other).map(UnwrappedCast::unwrapped_cast)
2471 }
2472
2473 /// Adds a list of [`Integer`] values.
2474 ///
2475 /// The following are implemented with the returned [incomplete-computation
2476 /// value][icv] as `Src`:
2477 /// * <code>[Assign]\<Src> for [Integer]</code>
2478 /// * <code>[From]\<Src> for [Integer]</code>
2479 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
2480 /// * <code>[AddAssign]\<Src> for [Integer]</code>
2481 /// * <code>[Add]\<Src> for [Integer]</code>,
2482 /// <code>[Add]\<[Integer]> for Src</code>
2483 /// * <code>[SubAssign]\<Src> for [Integer]</code>,
2484 /// <code>[SubFrom]\<Src> for [Integer]</code>
2485 /// * <code>[Sub]\<Src> for [Integer]</code>,
2486 /// <code>[Sub]\<[Integer]> for Src</code>
2487 ///
2488 /// # Examples
2489 ///
2490 /// ```rust
2491 /// use rug::{Complete, Integer};
2492 ///
2493 /// let values = [
2494 /// Integer::from(5),
2495 /// Integer::from(1024),
2496 /// Integer::from(-100_000),
2497 /// Integer::from(-4),
2498 /// ];
2499 ///
2500 /// let sum = Integer::sum(values.iter()).complete();
2501 /// let expected = 5 + 1024 - 100_000 - 4;
2502 /// assert_eq!(sum, expected);
2503 /// ```
2504 ///
2505 /// [icv]: crate#incomplete-computation-values
2506 #[inline]
2507 pub fn sum<'a, I>(values: I) -> SumIncomplete<'a, I>
2508 where
2509 I: Iterator<Item = &'a Self>,
2510 {
2511 SumIncomplete { values }
2512 }
2513
2514 /// Finds the dot product of a list of [`Integer`] value pairs.
2515 ///
2516 /// The following are implemented with the returned [incomplete-computation
2517 /// value][icv] as `Src`:
2518 /// * <code>[Assign]\<Src> for [Integer]</code>
2519 /// * <code>[From]\<Src> for [Integer]</code>
2520 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
2521 /// * <code>[AddAssign]\<Src> for [Integer]</code>
2522 /// * <code>[Add]\<Src> for [Integer]</code>,
2523 /// <code>[Add]\<[Integer]> for Src</code>
2524 /// * <code>[SubAssign]\<Src> for [Integer]</code>,
2525 /// <code>[SubFrom]\<Src> for [Integer]</code>
2526 /// * <code>[Sub]\<Src> for [Integer]</code>,
2527 /// <code>[Sub]\<[Integer]> for Src</code>
2528 ///
2529 /// # Examples
2530 ///
2531 /// ```rust
2532 /// use rug::{Complete, Integer};
2533 ///
2534 /// let a = [Integer::from(270), Integer::from(-11)];
2535 /// let b = [Integer::from(100), Integer::from(5)];
2536 ///
2537 /// let dot = Integer::dot(a.iter().zip(b.iter())).complete();
2538 /// let expected = 270 * 100 - 11 * 5;
2539 /// assert_eq!(dot, expected);
2540 /// ```
2541 ///
2542 /// [icv]: crate#incomplete-computation-values
2543 #[inline]
2544 pub fn dot<'a, I>(values: I) -> DotIncomplete<'a, I>
2545 where
2546 I: Iterator<Item = (&'a Self, &'a Self)>,
2547 {
2548 DotIncomplete { values }
2549 }
2550
2551 /// Multiplies a list of [`Integer`] values.
2552 ///
2553 /// The following are implemented with the returned [incomplete-computation
2554 /// value][icv] as `Src`:
2555 /// * <code>[Assign]\<Src> for [Integer]</code>
2556 /// * <code>[From]\<Src> for [Integer]</code>
2557 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
2558 /// * <code>[MulAssign]\<Src> for [Integer]</code>
2559 /// * <code>[Mul]\<Src> for [Integer]</code>,
2560 /// <code>[Mul]\<[Integer]> for Src</code>
2561 ///
2562 /// # Examples
2563 ///
2564 /// ```rust
2565 /// use rug::{Complete, Integer};
2566 ///
2567 /// let values = [
2568 /// Integer::from(5),
2569 /// Integer::from(1024),
2570 /// Integer::from(-100_000),
2571 /// Integer::from(-4),
2572 /// ];
2573 ///
2574 /// let product = Integer::product(values.iter()).complete();
2575 /// let expected = 5 * 1024 * -100_000 * -4;
2576 /// assert_eq!(product, expected);
2577 /// ```
2578 ///
2579 /// [icv]: crate#incomplete-computation-values
2580 #[inline]
2581 pub fn product<'a, I>(values: I) -> ProductIncomplete<'a, I>
2582 where
2583 I: Iterator<Item = &'a Self>,
2584 {
2585 ProductIncomplete { values }
2586 }
2587
2588 /// Computes the absolute value.
2589 ///
2590 /// # Examples
2591 ///
2592 /// ```rust
2593 /// use rug::Integer;
2594 /// let i = Integer::from(-100);
2595 /// let abs = i.abs();
2596 /// assert_eq!(abs, 100);
2597 /// ```
2598 #[inline]
2599 #[must_use]
2600 pub fn abs(mut self) -> Self {
2601 self.abs_mut();
2602 self
2603 }
2604
2605 /// Computes the absolute value.
2606 ///
2607 /// # Examples
2608 ///
2609 /// ```rust
2610 /// use rug::Integer;
2611 /// let mut i = Integer::from(-100);
2612 /// i.abs_mut();
2613 /// assert_eq!(i, 100);
2614 /// ```
2615 #[inline]
2616 pub fn abs_mut(&mut self) {
2617 xmpz::abs(self, ());
2618 }
2619
2620 /// Computes the absolute value.
2621 ///
2622 /// The following are implemented with the returned [incomplete-computation
2623 /// value][icv] as `Src`:
2624 /// * <code>[Assign]\<Src> for [Integer]</code>
2625 /// * <code>[From]\<Src> for [Integer]</code>
2626 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
2627 ///
2628 /// # Examples
2629 ///
2630 /// ```rust
2631 /// use rug::Integer;
2632 /// let i = Integer::from(-100);
2633 /// let r = i.abs_ref();
2634 /// let abs = Integer::from(r);
2635 /// assert_eq!(abs, 100);
2636 /// assert_eq!(i, -100);
2637 /// ```
2638 ///
2639 /// [icv]: crate#incomplete-computation-values
2640 #[inline]
2641 pub fn abs_ref(&self) -> AbsIncomplete {
2642 AbsIncomplete { ref_self: self }
2643 }
2644
2645 /// Computes the signum.
2646 ///
2647 /// * 0 if the value is zero
2648 /// * 1 if the value is positive
2649 /// * −1 if the value is negative
2650 ///
2651 /// # Examples
2652 ///
2653 /// ```rust
2654 /// use rug::Integer;
2655 /// assert_eq!(Integer::from(-100).signum(), -1);
2656 /// assert_eq!(Integer::from(0).signum(), 0);
2657 /// assert_eq!(Integer::from(100).signum(), 1);
2658 /// ```
2659 #[inline]
2660 #[must_use]
2661 pub fn signum(mut self) -> Self {
2662 self.signum_mut();
2663 self
2664 }
2665
2666 /// Computes the signum.
2667 ///
2668 /// * 0 if the value is zero
2669 /// * 1 if the value is positive
2670 /// * −1 if the value is negative
2671 ///
2672 /// # Examples
2673 ///
2674 /// ```rust
2675 /// use rug::Integer;
2676 /// let mut i = Integer::from(-100);
2677 /// i.signum_mut();
2678 /// assert_eq!(i, -1);
2679 /// ```
2680 #[inline]
2681 pub fn signum_mut(&mut self) {
2682 xmpz::signum(self, ());
2683 }
2684
2685 /// Computes the signum.
2686 ///
2687 /// * 0 if the value is zero
2688 /// * 1 if the value is positive
2689 /// * −1 if the value is negative
2690 ///
2691 /// The following are implemented with the returned [incomplete-computation
2692 /// value][icv] as `Src`:
2693 /// * <code>[Assign]\<Src> for [Integer]</code>
2694 /// * <code>[From]\<Src> for [Integer]</code>
2695 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
2696 ///
2697 /// # Examples
2698 ///
2699 /// ```rust
2700 /// use rug::Integer;
2701 /// let i = Integer::from(-100);
2702 /// let r = i.signum_ref();
2703 /// let signum = Integer::from(r);
2704 /// assert_eq!(signum, -1);
2705 /// assert_eq!(i, -100);
2706 /// ```
2707 ///
2708 /// [icv]: crate#incomplete-computation-values
2709 #[inline]
2710 pub fn signum_ref(&self) -> SignumIncomplete {
2711 SignumIncomplete { ref_self: self }
2712 }
2713
2714 /// Clamps the value within the specified bounds.
2715 ///
2716 /// # Panics
2717 ///
2718 /// Panics if the maximum value is less than the minimum value.
2719 ///
2720 /// # Examples
2721 ///
2722 /// ```rust
2723 /// use rug::Integer;
2724 /// let min = -10;
2725 /// let max = 10;
2726 /// let too_small = Integer::from(-100);
2727 /// let clamped1 = too_small.clamp(&min, &max);
2728 /// assert_eq!(clamped1, -10);
2729 /// let in_range = Integer::from(3);
2730 /// let clamped2 = in_range.clamp(&min, &max);
2731 /// assert_eq!(clamped2, 3);
2732 /// ```
2733 #[inline]
2734 #[must_use]
2735 pub fn clamp<Min, Max>(mut self, min: &Min, max: &Max) -> Self
2736 where
2737 Self: PartialOrd<Min> + PartialOrd<Max> + for<'a> Assign<&'a Min> + for<'a> Assign<&'a Max>,
2738 {
2739 self.clamp_mut(min, max);
2740 self
2741 }
2742
2743 /// Clamps the value within the specified bounds.
2744 ///
2745 /// # Panics
2746 ///
2747 /// Panics if the maximum value is less than the minimum value.
2748 ///
2749 /// # Examples
2750 ///
2751 /// ```rust
2752 /// use rug::Integer;
2753 /// let min = -10;
2754 /// let max = 10;
2755 /// let mut too_small = Integer::from(-100);
2756 /// too_small.clamp_mut(&min, &max);
2757 /// assert_eq!(too_small, -10);
2758 /// let mut in_range = Integer::from(3);
2759 /// in_range.clamp_mut(&min, &max);
2760 /// assert_eq!(in_range, 3);
2761 /// ```
2762 pub fn clamp_mut<Min, Max>(&mut self, min: &Min, max: &Max)
2763 where
2764 Self: PartialOrd<Min> + PartialOrd<Max> + for<'a> Assign<&'a Min> + for<'a> Assign<&'a Max>,
2765 {
2766 if (*self).lt(min) {
2767 self.assign(min);
2768 assert!(!(*self).gt(max), "minimum larger than maximum");
2769 } else if (*self).gt(max) {
2770 self.assign(max);
2771 assert!(!(*self).lt(min), "minimum larger than maximum");
2772 }
2773 }
2774
2775 /// Clamps the value within the specified bounds.
2776 ///
2777 /// The following are implemented with the returned [incomplete-computation
2778 /// value][icv] as `Src`:
2779 /// * <code>[Assign]\<Src> for [Integer]</code>
2780 /// * <code>[From]\<Src> for [Integer]</code>
2781 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
2782 ///
2783 /// # Panics
2784 ///
2785 /// Panics if the maximum value is less than the minimum value.
2786 ///
2787 /// # Examples
2788 ///
2789 /// ```rust
2790 /// use rug::Integer;
2791 /// let min = -10;
2792 /// let max = 10;
2793 /// let too_small = Integer::from(-100);
2794 /// let r1 = too_small.clamp_ref(&min, &max);
2795 /// let clamped1 = Integer::from(r1);
2796 /// assert_eq!(clamped1, -10);
2797 /// let in_range = Integer::from(3);
2798 /// let r2 = in_range.clamp_ref(&min, &max);
2799 /// let clamped2 = Integer::from(r2);
2800 /// assert_eq!(clamped2, 3);
2801 /// ```
2802 ///
2803 /// [icv]: crate#incomplete-computation-values
2804 #[inline]
2805 pub fn clamp_ref<'min, 'max, Min, Max>(
2806 &self,
2807 min: &'min Min,
2808 max: &'max Max,
2809 ) -> ClampIncomplete<'_, 'min, 'max, Min, Max>
2810 where
2811 Self: PartialOrd<Min> + PartialOrd<Max> + for<'a> Assign<&'a Min> + for<'a> Assign<&'a Max>,
2812 {
2813 ClampIncomplete {
2814 ref_self: self,
2815 min,
2816 max,
2817 }
2818 }
2819
2820 /// Keeps the <i>n</i> least significant bits only, producing a result that
2821 /// is greater or equal to 0.
2822 ///
2823 /// # Examples
2824 ///
2825 /// ```rust
2826 /// use rug::Integer;
2827 /// let i = Integer::from(-1);
2828 /// let keep_8 = i.keep_bits(8);
2829 /// assert_eq!(keep_8, 0xff);
2830 /// ```
2831 #[inline]
2832 #[must_use]
2833 pub fn keep_bits(mut self, n: u32) -> Self {
2834 self.keep_bits_mut(n);
2835 self
2836 }
2837
2838 /// Keeps the <i>n</i> least significant bits only, producing a result that
2839 /// is greater or equal to 0.
2840 ///
2841 /// # Examples
2842 ///
2843 /// ```rust
2844 /// use rug::Integer;
2845 /// let mut i = Integer::from(-1);
2846 /// i.keep_bits_mut(8);
2847 /// assert_eq!(i, 0xff);
2848 /// ```
2849 #[inline]
2850 pub fn keep_bits_mut(&mut self, n: u32) {
2851 xmpz::fdiv_r_2exp(self, (), n.into());
2852 }
2853
2854 /// Keeps the <i>n</i> least significant bits only, producing a result that
2855 /// is greater or equal to 0.
2856 ///
2857 /// The following are implemented with the returned [incomplete-computation
2858 /// value][icv] as `Src`:
2859 /// * <code>[Assign]\<Src> for [Integer]</code>
2860 /// * <code>[From]\<Src> for [Integer]</code>
2861 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
2862 ///
2863 /// # Examples
2864 ///
2865 /// ```rust
2866 /// use rug::Integer;
2867 /// let i = Integer::from(-1);
2868 /// let r = i.keep_bits_ref(8);
2869 /// let eight_bits = Integer::from(r);
2870 /// assert_eq!(eight_bits, 0xff);
2871 /// ```
2872 ///
2873 /// [icv]: crate#incomplete-computation-values
2874 #[inline]
2875 pub fn keep_bits_ref(&self, n: u32) -> KeepBitsIncomplete {
2876 let n = n.into();
2877 KeepBitsIncomplete { ref_self: self, n }
2878 }
2879
2880 /// Keeps the <i>n</i> least significant bits only, producing a negative
2881 /// result if the <i>n</i>th least significant bit is one.
2882 ///
2883 /// # Examples
2884 ///
2885 /// ```rust
2886 /// use rug::Integer;
2887 /// let i = Integer::from(-1);
2888 /// let i_keep_8 = i.keep_signed_bits(8);
2889 /// assert_eq!(i_keep_8, -1);
2890 /// let j = Integer::from(15 << 8 | 15);
2891 /// let j_keep_8 = j.keep_signed_bits(8);
2892 /// assert_eq!(j_keep_8, 15);
2893 /// ```
2894 #[inline]
2895 #[must_use]
2896 pub fn keep_signed_bits(mut self, n: u32) -> Self {
2897 self.keep_signed_bits_mut(n);
2898 self
2899 }
2900
2901 /// Keeps the <i>n</i> least significant bits only, producing a negative
2902 /// result if the <i>n</i>th least significant bit is one.
2903 ///
2904 /// # Examples
2905 ///
2906 /// ```rust
2907 /// use rug::Integer;
2908 /// let mut i = Integer::from(-1);
2909 /// i.keep_signed_bits_mut(8);
2910 /// assert_eq!(i, -1);
2911 /// let mut j = Integer::from(15 << 8 | 15);
2912 /// j.keep_signed_bits_mut(8);
2913 /// assert_eq!(j, 15);
2914 /// ```
2915 #[inline]
2916 pub fn keep_signed_bits_mut(&mut self, n: u32) {
2917 xmpz::keep_signed_bits(self, (), n.into());
2918 }
2919
2920 /// Keeps the <i>n</i> least significant bits only, producing a negative
2921 /// result if the <i>n</i>th least significant bit is one.
2922 ///
2923 /// The following are implemented with the returned
2924 /// [incomplete-computation value][icv] as `Src`:
2925 /// * <code>[Assign]\<Src> for [Integer]</code>
2926 /// * <code>[From]\<Src> for [Integer]</code>
2927 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
2928 ///
2929 /// # Examples
2930 ///
2931 /// ```rust
2932 /// use rug::Integer;
2933 /// let i = Integer::from(-1);
2934 /// let r = i.keep_signed_bits_ref(8);
2935 /// let eight_bits = Integer::from(r);
2936 /// assert_eq!(eight_bits, -1);
2937 /// ```
2938 ///
2939 /// [icv]: crate#incomplete-computation-values
2940 #[inline]
2941 pub fn keep_signed_bits_ref(&self, n: u32) -> KeepSignedBitsIncomplete<'_> {
2942 let n = n.into();
2943 KeepSignedBitsIncomplete { ref_self: self, n }
2944 }
2945
2946 /// Finds the next power of two, or 1 if the number ≤ 0.
2947 ///
2948 /// # Examples
2949 ///
2950 /// ```rust
2951 /// use rug::Integer;
2952 /// let i = Integer::from(-3).next_power_of_two();
2953 /// assert_eq!(i, 1);
2954 /// let i = Integer::from(4).next_power_of_two();
2955 /// assert_eq!(i, 4);
2956 /// let i = Integer::from(7).next_power_of_two();
2957 /// assert_eq!(i, 8);
2958 /// ```
2959 #[inline]
2960 #[must_use]
2961 pub fn next_power_of_two(mut self) -> Self {
2962 self.next_power_of_two_mut();
2963 self
2964 }
2965
2966 /// Finds the next power of two, or 1 if the number ≤ 0.
2967 ///
2968 /// # Examples
2969 ///
2970 /// ```rust
2971 /// use rug::Integer;
2972 /// let mut i = Integer::from(53);
2973 /// i.next_power_of_two_mut();
2974 /// assert_eq!(i, 64);
2975 /// ```
2976 #[inline]
2977 pub fn next_power_of_two_mut(&mut self) {
2978 xmpz::next_pow_of_two(self, ());
2979 }
2980
2981 /// Finds the next power of two, or 1 if the number ≤ 0.
2982 ///
2983 /// The following are implemented with the returned [incomplete-computation
2984 /// value][icv] as `Src`:
2985 /// * <code>[Assign]\<Src> for [Integer]</code>
2986 /// * <code>[From]\<Src> for [Integer]</code>
2987 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
2988 ///
2989 /// # Examples
2990 ///
2991 /// ```rust
2992 /// use rug::Integer;
2993 /// let i = Integer::from(53);
2994 /// let r = i.next_power_of_two_ref();
2995 /// let next = Integer::from(r);
2996 /// assert_eq!(next, 64);
2997 /// ```
2998 ///
2999 /// [icv]: crate#incomplete-computation-values
3000 #[inline]
3001 pub fn next_power_of_two_ref(&self) -> NextPowerOfTwoIncomplete<'_> {
3002 NextPowerOfTwoIncomplete { ref_self: self }
3003 }
3004
3005 /// Finds the modulus, or the remainder of Euclidean division.
3006 ///
3007 /// The result is always zero or positive.
3008 ///
3009 /// # Panics
3010 ///
3011 /// Panics if `divisor` is zero.
3012 ///
3013 /// # Examples
3014 ///
3015 /// ```rust
3016 /// use rug::Integer;
3017 /// let dividend = Integer::from(-1003);
3018 /// let divisor = Integer::from(-10);
3019 /// let modulus = dividend.modulo(&divisor);
3020 /// assert_eq!(modulus, 7);
3021 /// ```
3022 #[inline]
3023 #[must_use]
3024 #[doc(alias = "rem_euclid")]
3025 pub fn modulo(mut self, divisor: &Self) -> Self {
3026 self.modulo_mut(divisor);
3027 self
3028 }
3029
3030 /// Finds the modulus, or the remainder of Euclidean division.
3031 ///
3032 /// The result is always zero or positive.
3033 ///
3034 /// # Panics
3035 ///
3036 /// Panics if `divisor` is zero.
3037 ///
3038 /// # Examples
3039 ///
3040 /// ```rust
3041 /// use rug::Integer;
3042 /// let mut m = Integer::from(-1003);
3043 /// let divisor = Integer::from(-10);
3044 /// m.modulo_mut(&divisor);
3045 /// assert_eq!(m, 7);
3046 /// ```
3047 #[inline]
3048 pub fn modulo_mut(&mut self, divisor: &Self) {
3049 xmpz::modulo(self, (), divisor);
3050 }
3051
3052 /// Finds the modulus, or the remainder of Euclidean division `dividend` /
3053 /// `self`.
3054 ///
3055 /// The result is always zero or positive.
3056 ///
3057 /// # Panics
3058 ///
3059 /// Panics if `self` is zero.
3060 ///
3061 /// # Examples
3062 ///
3063 /// ```rust
3064 /// use rug::Integer;
3065 /// let dividend = Integer::from(-1003);
3066 /// let mut m = Integer::from(-10);
3067 /// m.modulo_from(÷nd);
3068 /// assert_eq!(m, 7);
3069 /// ```
3070 #[inline]
3071 pub fn modulo_from(&mut self, dividend: &Self) {
3072 xmpz::modulo(self, dividend, ());
3073 }
3074
3075 /// Finds the modulus, or the remainder of Euclidean division.
3076 ///
3077 /// The result is always zero or positive.
3078 ///
3079 /// The following are implemented with the returned [incomplete-computation
3080 /// value][icv] as `Src`:
3081 /// * <code>[Assign]\<Src> for [Integer]</code>
3082 /// * <code>[From]\<Src> for [Integer]</code>
3083 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
3084 ///
3085 /// # Examples
3086 ///
3087 /// ```rust
3088 /// use rug::Integer;
3089 /// let dividend = Integer::from(-1003);
3090 /// let divisor = Integer::from(-10);
3091 /// let r = dividend.modulo_ref(&divisor);
3092 /// let modulus = Integer::from(r);
3093 /// assert_eq!(modulus, 7);
3094 /// ```
3095 ///
3096 /// [icv]: crate#incomplete-computation-values
3097 pub fn modulo_ref<'a>(&'a self, divisor: &'a Self) -> ModuloIncomplete<'a> {
3098 ModuloIncomplete {
3099 ref_self: self,
3100 divisor,
3101 }
3102 }
3103
3104 /// Performs a division producing both the quotient and remainder.
3105 ///
3106 /// The remainder has the same sign as the dividend.
3107 ///
3108 /// # Panics
3109 ///
3110 /// Panics if `divisor` is zero.
3111 ///
3112 /// # Examples
3113 ///
3114 /// ```rust
3115 /// use rug::Integer;
3116 /// let dividend = Integer::from(23);
3117 /// let divisor = Integer::from(-10);
3118 /// let (quotient, rem) = dividend.div_rem(divisor);
3119 /// assert_eq!(quotient, -2);
3120 /// assert_eq!(rem, 3);
3121 /// ```
3122 #[inline]
3123 pub fn div_rem(mut self, mut divisor: Self) -> (Self, Self) {
3124 self.div_rem_mut(&mut divisor);
3125 (self, divisor)
3126 }
3127
3128 /// Performs a division producing both the quotient and remainder.
3129 ///
3130 /// The remainder has the same sign as the dividend.
3131 ///
3132 /// The quotient is stored in `self` and the remainder is stored in
3133 /// `divisor`.
3134 ///
3135 /// # Panics
3136 ///
3137 /// Panics if `divisor` is zero.
3138 ///
3139 /// # Examples
3140 ///
3141 /// ```rust
3142 /// use rug::Integer;
3143 /// let mut dividend_quotient = Integer::from(-23);
3144 /// let mut divisor_rem = Integer::from(10);
3145 /// dividend_quotient.div_rem_mut(&mut divisor_rem);
3146 /// assert_eq!(dividend_quotient, -2);
3147 /// assert_eq!(divisor_rem, -3);
3148 /// ```
3149 #[inline]
3150 pub fn div_rem_mut(&mut self, divisor: &mut Self) {
3151 xmpz::tdiv_qr(self, divisor, (), ());
3152 }
3153
3154 /// Performs a division producing both the quotient and remainder.
3155 ///
3156 /// The following are implemented with the returned [incomplete-computation
3157 /// value][icv] as `Src`:
3158 /// * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
3159 /// * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
3160 /// * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
3161 /// * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
3162 ///
3163 /// The remainder has the same sign as the dividend.
3164 ///
3165 /// # Examples
3166 ///
3167 /// ```rust
3168 /// use rug::{Complete, Integer};
3169 /// let dividend = Integer::from(-23);
3170 /// let divisor = Integer::from(-10);
3171 /// let (quotient, rem) = dividend.div_rem_ref(&divisor).complete();
3172 /// assert_eq!(quotient, 2);
3173 /// assert_eq!(rem, -3);
3174 /// ```
3175 ///
3176 /// [icv]: crate#incomplete-computation-values
3177 #[inline]
3178 pub fn div_rem_ref<'a>(&'a self, divisor: &'a Self) -> DivRemIncomplete<'a> {
3179 DivRemIncomplete {
3180 ref_self: self,
3181 divisor,
3182 }
3183 }
3184
3185 /// Performs a division producing both the quotient and remainder, with the
3186 /// quotient rounded up.
3187 ///
3188 /// The sign of the remainder is the opposite of the divisor’s sign.
3189 ///
3190 /// # Panics
3191 ///
3192 /// Panics if `divisor` is zero.
3193 ///
3194 /// # Examples
3195 ///
3196 /// ```rust
3197 /// use rug::Integer;
3198 /// let dividend = Integer::from(23);
3199 /// let divisor = Integer::from(-10);
3200 /// let (quotient, rem) = dividend.div_rem_ceil(divisor);
3201 /// assert_eq!(quotient, -2);
3202 /// assert_eq!(rem, 3);
3203 /// ```
3204 #[inline]
3205 pub fn div_rem_ceil(mut self, mut divisor: Self) -> (Self, Self) {
3206 self.div_rem_ceil_mut(&mut divisor);
3207 (self, divisor)
3208 }
3209
3210 /// Performs a division producing both the quotient and remainder, with the
3211 /// quotient rounded up.
3212 ///
3213 /// The sign of the remainder is the opposite of the divisor’s sign.
3214 ///
3215 /// The quotient is stored in `self` and the remainder is stored in
3216 /// `divisor`.
3217 ///
3218 /// # Panics
3219 ///
3220 /// Panics if `divisor` is zero.
3221 ///
3222 /// # Examples
3223 ///
3224 /// ```rust
3225 /// use rug::Integer;
3226 /// let mut dividend_quotient = Integer::from(-23);
3227 /// let mut divisor_rem = Integer::from(10);
3228 /// dividend_quotient.div_rem_ceil_mut(&mut divisor_rem);
3229 /// assert_eq!(dividend_quotient, -2);
3230 /// assert_eq!(divisor_rem, -3);
3231 /// ```
3232 #[inline]
3233 pub fn div_rem_ceil_mut(&mut self, divisor: &mut Self) {
3234 xmpz::cdiv_qr(self, divisor, (), ());
3235 }
3236
3237 /// Performs a division producing both the quotient and remainder, with the
3238 /// quotient rounded up.
3239 ///
3240 /// The sign of the remainder is the opposite of the divisor’s sign.
3241 ///
3242 /// The following are implemented with the returned [incomplete-computation
3243 /// value][icv] as `Src`:
3244 /// * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
3245 /// * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
3246 /// * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
3247 /// * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
3248 ///
3249 /// # Examples
3250 ///
3251 /// ```rust
3252 /// use rug::{Complete, Integer};
3253 /// let dividend = Integer::from(-23);
3254 /// let divisor = Integer::from(-10);
3255 /// let (quotient, rem) = dividend.div_rem_ceil_ref(&divisor).complete();
3256 /// assert_eq!(quotient, 3);
3257 /// assert_eq!(rem, 7);
3258 /// ```
3259 ///
3260 /// [icv]: crate#incomplete-computation-values
3261 #[inline]
3262 pub fn div_rem_ceil_ref<'a>(&'a self, divisor: &'a Self) -> DivRemCeilIncomplete<'a> {
3263 DivRemCeilIncomplete {
3264 ref_self: self,
3265 divisor,
3266 }
3267 }
3268
3269 /// Performs a division producing both the quotient and remainder, with the
3270 /// quotient rounded down.
3271 ///
3272 /// The remainder has the same sign as the divisor.
3273 ///
3274 /// # Panics
3275 ///
3276 /// Panics if `divisor` is zero.
3277 ///
3278 /// # Examples
3279 ///
3280 /// ```rust
3281 /// use rug::Integer;
3282 /// let dividend = Integer::from(23);
3283 /// let divisor = Integer::from(-10);
3284 /// let (quotient, rem) = dividend.div_rem_floor(divisor);
3285 /// assert_eq!(quotient, -3);
3286 /// assert_eq!(rem, -7);
3287 /// ```
3288 #[inline]
3289 pub fn div_rem_floor(mut self, mut divisor: Self) -> (Self, Self) {
3290 self.div_rem_floor_mut(&mut divisor);
3291 (self, divisor)
3292 }
3293
3294 /// Performs a division producing both the quotient and remainder, with the
3295 /// quotient rounded down.
3296 ///
3297 /// The remainder has the same sign as the divisor.
3298 ///
3299 /// The quotient is stored in `self` and the remainder is stored in
3300 /// `divisor`.
3301 ///
3302 /// # Panics
3303 ///
3304 /// Panics if `divisor` is zero.
3305 ///
3306 /// # Examples
3307 ///
3308 /// ```rust
3309 /// use rug::Integer;
3310 /// let mut dividend_quotient = Integer::from(-23);
3311 /// let mut divisor_rem = Integer::from(10);
3312 /// dividend_quotient.div_rem_floor_mut(&mut divisor_rem);
3313 /// assert_eq!(dividend_quotient, -3);
3314 /// assert_eq!(divisor_rem, 7);
3315 /// ```
3316 #[inline]
3317 pub fn div_rem_floor_mut(&mut self, divisor: &mut Self) {
3318 xmpz::fdiv_qr(self, divisor, (), ());
3319 }
3320
3321 /// Performs a division producing both the quotient and remainder, with the
3322 /// quotient rounded down.
3323 ///
3324 /// The remainder has the same sign as the divisor.
3325 ///
3326 /// The following are implemented with the returned [incomplete-computation
3327 /// value][icv] as `Src`:
3328 /// * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
3329 /// * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
3330 /// * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
3331 /// * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
3332 ///
3333 /// # Examples
3334 ///
3335 /// ```rust
3336 /// use rug::{Complete, Integer};
3337 /// let dividend = Integer::from(-23);
3338 /// let divisor = Integer::from(-10);
3339 /// let (quotient, rem) = dividend.div_rem_floor_ref(&divisor).complete();
3340 /// assert_eq!(quotient, 2);
3341 /// assert_eq!(rem, -3);
3342 /// ```
3343 ///
3344 /// [icv]: crate#incomplete-computation-values
3345 #[inline]
3346 pub fn div_rem_floor_ref<'a>(&'a self, divisor: &'a Self) -> DivRemFloorIncomplete<'a> {
3347 DivRemFloorIncomplete {
3348 ref_self: self,
3349 divisor,
3350 }
3351 }
3352
3353 /// Performs a division producing both the quotient and remainder, with the
3354 /// quotient rounded to the nearest integer.
3355 ///
3356 /// When the quotient before rounding lies exactly between two integers, it
3357 /// is rounded away from zero.
3358 ///
3359 /// # Panics
3360 ///
3361 /// Panics if `divisor` is zero.
3362 ///
3363 /// # Examples
3364 ///
3365 /// ```rust
3366 /// use rug::Integer;
3367 /// // 23 / -10 → -2 rem 3
3368 /// let (q, rem) = Integer::from(23).div_rem_round((-10).into());
3369 /// assert!(q == -2 && rem == 3);
3370 /// // 25 / 10 → 3 rem -5
3371 /// let (q, rem) = Integer::from(25).div_rem_round(10.into());
3372 /// assert!(q == 3 && rem == -5);
3373 /// // -27 / 10 → -3 rem 3
3374 /// let (q, rem) = Integer::from(-27).div_rem_round(10.into());
3375 /// assert!(q == -3 && rem == 3);
3376 /// ```
3377 #[inline]
3378 pub fn div_rem_round(mut self, mut divisor: Self) -> (Self, Self) {
3379 self.div_rem_round_mut(&mut divisor);
3380 (self, divisor)
3381 }
3382
3383 /// Performs a division producing both the quotient and remainder, with the
3384 /// quotient rounded to the nearest integer.
3385 ///
3386 /// When the quotient before rounding lies exactly between two integers, it
3387 /// is rounded away from zero.
3388 ///
3389 /// # Panics
3390 ///
3391 /// Panics if `divisor` is zero.
3392 ///
3393 /// # Examples
3394 ///
3395 /// ```rust
3396 /// use rug::Integer;
3397 /// // -25 / -10 → 3 rem 5
3398 /// let mut dividend_quotient = Integer::from(-25);
3399 /// let mut divisor_rem = Integer::from(-10);
3400 /// dividend_quotient.div_rem_round_mut(&mut divisor_rem);
3401 /// assert_eq!(dividend_quotient, 3);
3402 /// assert_eq!(divisor_rem, 5);
3403 /// ```
3404 #[inline]
3405 pub fn div_rem_round_mut(&mut self, divisor: &mut Self) {
3406 xmpz::rdiv_qr(self, divisor, (), ());
3407 }
3408
3409 /// Performs a division producing both the quotient and remainder, with the
3410 /// quotient rounded to the nearest integer.
3411 ///
3412 /// When the quotient before rounding lies exactly between two integers, it
3413 /// is rounded away from zero.
3414 ///
3415 /// The following are implemented with the returned [incomplete-computation
3416 /// value][icv] as `Src`:
3417 /// * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
3418 /// * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
3419 /// * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
3420 /// * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
3421 ///
3422 /// # Examples
3423 ///
3424 /// ```rust
3425 /// use rug::{Complete, Integer};
3426 /// // -28 / -10 → 3 rem 2
3427 /// let dividend = Integer::from(-28);
3428 /// let divisor = Integer::from(-10);
3429 /// let (quotient, rem) = dividend.div_rem_round_ref(&divisor).complete();
3430 /// assert_eq!(quotient, 3);
3431 /// assert_eq!(rem, 2);
3432 /// ```
3433 ///
3434 /// [icv]: crate#incomplete-computation-values
3435 #[inline]
3436 pub fn div_rem_round_ref<'a>(&'a self, divisor: &'a Self) -> DivRemRoundIncomplete<'a> {
3437 DivRemRoundIncomplete {
3438 ref_self: self,
3439 divisor,
3440 }
3441 }
3442
3443 /// Performs Euclidean division producing both the quotient and remainder,
3444 /// with a positive remainder.
3445 ///
3446 /// # Panics
3447 ///
3448 /// Panics if `divisor` is zero.
3449 ///
3450 /// # Examples
3451 ///
3452 /// ```rust
3453 /// use rug::Integer;
3454 /// let dividend = Integer::from(23);
3455 /// let divisor = Integer::from(-10);
3456 /// let (quotient, rem) = dividend.div_rem_euc(divisor);
3457 /// assert_eq!(quotient, -2);
3458 /// assert_eq!(rem, 3);
3459 /// ```
3460 #[inline]
3461 pub fn div_rem_euc(mut self, mut divisor: Self) -> (Self, Self) {
3462 self.div_rem_euc_mut(&mut divisor);
3463 (self, divisor)
3464 }
3465
3466 /// Performs Euclidean division producing both the quotient and remainder,
3467 /// with a positive remainder.
3468 ///
3469 /// The quotient is stored in `self` and the remainder is stored in
3470 /// `divisor`.
3471 ///
3472 /// # Panics
3473 ///
3474 /// Panics if `divisor` is zero.
3475 ///
3476 /// # Examples
3477 ///
3478 /// ```rust
3479 /// use rug::Integer;
3480 /// let mut dividend_quotient = Integer::from(-23);
3481 /// let mut divisor_rem = Integer::from(10);
3482 /// dividend_quotient.div_rem_euc_mut(&mut divisor_rem);
3483 /// assert_eq!(dividend_quotient, -3);
3484 /// assert_eq!(divisor_rem, 7);
3485 /// ```
3486 #[inline]
3487 pub fn div_rem_euc_mut(&mut self, divisor: &mut Self) {
3488 xmpz::ediv_qr(self, divisor, (), ());
3489 }
3490
3491 /// Performs Euclidan division producing both the quotient and remainder,
3492 /// with a positive remainder.
3493 ///
3494 /// The following are implemented with the returned [incomplete-computation
3495 /// value][icv] as `Src`:
3496 /// * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
3497 /// * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
3498 /// * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
3499 /// * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
3500 ///
3501 /// # Examples
3502 ///
3503 /// ```rust
3504 /// use rug::{Complete, Integer};
3505 /// let dividend = Integer::from(-23);
3506 /// let divisor = Integer::from(-10);
3507 /// let (quotient, rem) = dividend.div_rem_euc_ref(&divisor).complete();
3508 /// assert_eq!(quotient, 3);
3509 /// assert_eq!(rem, 7);
3510 /// ```
3511 ///
3512 /// [icv]: crate#incomplete-computation-values
3513 #[inline]
3514 pub fn div_rem_euc_ref<'a>(&'a self, divisor: &'a Self) -> DivRemEucIncomplete<'a> {
3515 DivRemEucIncomplete {
3516 ref_self: self,
3517 divisor,
3518 }
3519 }
3520
3521 /// Returns the modulo, or the remainder of Euclidean division by a [`u32`].
3522 ///
3523 /// The result is always zero or positive.
3524 ///
3525 /// # Panics
3526 ///
3527 /// Panics if `modulo` is zero.
3528 ///
3529 /// # Examples
3530 ///
3531 /// ```rust
3532 /// use rug::Integer;
3533 /// let pos = Integer::from(23);
3534 /// assert_eq!(pos.mod_u(1), 0);
3535 /// assert_eq!(pos.mod_u(10), 3);
3536 /// assert_eq!(pos.mod_u(100), 23);
3537 /// let neg = Integer::from(-23);
3538 /// assert_eq!(neg.mod_u(1), 0);
3539 /// assert_eq!(neg.mod_u(10), 7);
3540 /// assert_eq!(neg.mod_u(100), 77);
3541 /// ```
3542 #[inline]
3543 pub fn mod_u(&self, modulo: u32) -> u32 {
3544 xmpz::fdiv_ui(self, modulo.into()).wrapping_cast()
3545 }
3546
3547 /// Performs an exact division.
3548 ///
3549 /// This is much faster than normal division, but produces correct results
3550 /// only when the division is exact.
3551 ///
3552 /// # Panics
3553 ///
3554 /// Panics if `divisor` is zero.
3555 ///
3556 /// # Examples
3557 ///
3558 /// ```rust
3559 /// use rug::Integer;
3560 /// let i = Integer::from(12345 * 54321);
3561 /// let quotient = i.div_exact(&Integer::from(12345));
3562 /// assert_eq!(quotient, 54321);
3563 /// ```
3564 #[inline]
3565 #[must_use]
3566 pub fn div_exact(mut self, divisor: &Self) -> Self {
3567 self.div_exact_mut(divisor);
3568 self
3569 }
3570
3571 /// Performs an exact division.
3572 ///
3573 /// This is much faster than normal division, but produces correct results
3574 /// only when the division is exact.
3575 ///
3576 /// # Panics
3577 ///
3578 /// Panics if `divisor` is zero.
3579 ///
3580 /// # Examples
3581 ///
3582 /// ```rust
3583 /// use rug::Integer;
3584 /// let mut i = Integer::from(12345 * 54321);
3585 /// i.div_exact_mut(&Integer::from(12345));
3586 /// assert_eq!(i, 54321);
3587 /// ```
3588 #[inline]
3589 pub fn div_exact_mut(&mut self, divisor: &Self) {
3590 xmpz::divexact(self, (), divisor);
3591 }
3592
3593 /// Performs an exact division `dividend` / `self`.
3594 ///
3595 /// This is much faster than normal division, but produces correct results
3596 /// only when the division is exact.
3597 ///
3598 /// # Panics
3599 ///
3600 /// Panics if `self` is zero.
3601 ///
3602 /// # Examples
3603 ///
3604 /// ```rust
3605 /// use rug::Integer;
3606 /// let mut i = Integer::from(12345);
3607 /// i.div_exact_from(&Integer::from(12345 * 54321));
3608 /// assert_eq!(i, 54321);
3609 /// ```
3610 pub fn div_exact_from(&mut self, dividend: &Integer) {
3611 xmpz::divexact(self, dividend, ());
3612 }
3613
3614 /// Performs an exact division.
3615 ///
3616 /// This is much faster than normal division, but produces correct results
3617 /// only when the division is exact.
3618 ///
3619 /// The following are implemented with the returned [incomplete-computation
3620 /// value][icv] as `Src`:
3621 /// * <code>[Assign]\<Src> for [Integer]</code>
3622 /// * <code>[From]\<Src> for [Integer]</code>
3623 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
3624 ///
3625 /// # Examples
3626 ///
3627 /// ```rust
3628 /// use rug::Integer;
3629 /// let i = Integer::from(12345 * 54321);
3630 /// let divisor = Integer::from(12345);
3631 /// let r = i.div_exact_ref(&divisor);
3632 /// let quotient = Integer::from(r);
3633 /// assert_eq!(quotient, 54321);
3634 /// ```
3635 ///
3636 /// [icv]: crate#incomplete-computation-values
3637 #[inline]
3638 pub fn div_exact_ref<'a>(&'a self, divisor: &'a Self) -> DivExactIncomplete<'a> {
3639 DivExactIncomplete {
3640 ref_self: self,
3641 divisor,
3642 }
3643 }
3644
3645 /// Performs an exact division.
3646 ///
3647 /// This is much faster than normal division, but produces correct results
3648 /// only when the division is exact.
3649 ///
3650 /// # Panics
3651 ///
3652 /// Panics if `divisor` is zero.
3653 ///
3654 /// # Examples
3655 ///
3656 /// ```rust
3657 /// use rug::Integer;
3658 /// let i = Integer::from(12345 * 54321);
3659 /// let q = i.div_exact_u(12345);
3660 /// assert_eq!(q, 54321);
3661 /// ```
3662 #[inline]
3663 #[must_use]
3664 pub fn div_exact_u(mut self, divisor: u32) -> Self {
3665 self.div_exact_u_mut(divisor);
3666 self
3667 }
3668
3669 /// Performs an exact division.
3670 ///
3671 /// This is much faster than normal division, but produces correct results
3672 /// only when the division is exact.
3673 ///
3674 /// # Panics
3675 ///
3676 /// Panics if `divisor` is zero.
3677 ///
3678 /// # Examples
3679 ///
3680 /// ```rust
3681 /// use rug::Integer;
3682 /// let mut i = Integer::from(12345 * 54321);
3683 /// i.div_exact_u_mut(12345);
3684 /// assert_eq!(i, 54321);
3685 /// ```
3686 #[inline]
3687 pub fn div_exact_u_mut(&mut self, divisor: u32) {
3688 xmpz::divexact_u32(self, (), divisor);
3689 }
3690
3691 /// Performs an exact division.
3692 ///
3693 /// This is much faster than normal division, but produces correct results
3694 /// only when the division is exact.
3695 ///
3696 /// The following are implemented with the returned [incomplete-computation
3697 /// value][icv] as `Src`:
3698 /// * <code>[Assign]\<Src> for [Integer]</code>
3699 /// * <code>[From]\<Src> for [Integer]</code>
3700 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
3701 ///
3702 /// # Examples
3703 ///
3704 /// ```rust
3705 /// use rug::Integer;
3706 /// let i = Integer::from(12345 * 54321);
3707 /// let r = i.div_exact_u_ref(12345);
3708 /// assert_eq!(Integer::from(r), 54321);
3709 /// ```
3710 ///
3711 /// [icv]: crate#incomplete-computation-values
3712 #[inline]
3713 pub fn div_exact_u_ref(&self, divisor: u32) -> DivExactUIncomplete<'_> {
3714 DivExactUIncomplete {
3715 ref_self: self,
3716 divisor,
3717 }
3718 }
3719
3720 /// Finds the inverse modulo `modulo` and returns [`Ok(inverse)`][Ok] if it
3721 /// exists, or [`Err(unchanged)`][Err] if the inverse does not exist.
3722 ///
3723 /// The inverse exists if the modulo is not zero, and `self` and the modulo
3724 /// are co-prime, that is their GCD is 1.
3725 ///
3726 /// # Examples
3727 ///
3728 /// ```rust
3729 /// use rug::Integer;
3730 /// let n = Integer::from(2);
3731 /// // Modulo 4, 2 has no inverse: there is no i such that 2 × i = 1.
3732 /// let inv_mod_4 = match n.invert(&Integer::from(4)) {
3733 /// Ok(_) => unreachable!(),
3734 /// Err(unchanged) => unchanged,
3735 /// };
3736 /// // no inverse exists, so value is unchanged
3737 /// assert_eq!(inv_mod_4, 2);
3738 /// let n = inv_mod_4;
3739 /// // Modulo 5, the inverse of 2 is 3, as 2 × 3 = 1.
3740 /// let inv_mod_5 = match n.invert(&Integer::from(5)) {
3741 /// Ok(inverse) => inverse,
3742 /// Err(_) => unreachable!(),
3743 /// };
3744 /// assert_eq!(inv_mod_5, 3);
3745 /// ```
3746 #[inline]
3747 pub fn invert(mut self, modulo: &Self) -> Result<Self, Self> {
3748 match self.invert_mut(modulo) {
3749 Ok(()) => Ok(self),
3750 Err(()) => Err(self),
3751 }
3752 }
3753
3754 /// Finds the inverse modulo `modulo` if an inverse exists.
3755 ///
3756 /// The inverse exists if the modulo is not zero, and `self` and the modulo
3757 /// are co-prime, that is their GCD is 1.
3758 ///
3759 /// # Examples
3760 ///
3761 /// ```rust
3762 /// use rug::Integer;
3763 /// let mut n = Integer::from(2);
3764 /// // Modulo 4, 2 has no inverse: there is no i such that 2 × i = 1.
3765 /// match n.invert_mut(&Integer::from(4)) {
3766 /// Ok(()) => unreachable!(),
3767 /// Err(()) => assert_eq!(n, 2),
3768 /// }
3769 /// // Modulo 5, the inverse of 2 is 3, as 2 × 3 = 1.
3770 /// match n.invert_mut(&Integer::from(5)) {
3771 /// Ok(()) => assert_eq!(n, 3),
3772 /// Err(()) => unreachable!(),
3773 /// }
3774 /// ```
3775 #[inline]
3776 #[allow(clippy::result_unit_err)]
3777 pub fn invert_mut(&mut self, modulo: &Self) -> Result<(), ()> {
3778 match self.invert_ref(modulo) {
3779 Some(InvertIncomplete { sinverse, .. }) => {
3780 xmpz::finish_invert(self, &sinverse, modulo);
3781 Ok(())
3782 }
3783 None => Err(()),
3784 }
3785 }
3786
3787 /// Finds the inverse modulo `modulo` if an inverse exists.
3788 ///
3789 /// The inverse exists if the modulo is not zero, and `self` and the modulo
3790 /// are co-prime, that is their GCD is 1.
3791 ///
3792 /// The following are implemented with the unwrapped returned
3793 /// [incomplete-computation value][icv] as `Src`:
3794 /// * <code>[Assign]\<Src> for [Integer]</code>
3795 /// * <code>[From]\<Src> for [Integer]</code>
3796 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
3797 ///
3798 /// # Examples
3799 ///
3800 /// ```rust
3801 /// use rug::Integer;
3802 /// let two = Integer::from(2);
3803 /// let four = Integer::from(4);
3804 /// let five = Integer::from(5);
3805 ///
3806 /// // Modulo 4, 2 has no inverse, there is no i such that 2 × i = 1.
3807 /// // For this conversion, if no inverse exists, the Integer
3808 /// // created is left unchanged as 0.
3809 /// assert!(two.invert_ref(&four).is_none());
3810 ///
3811 /// // Modulo 5, the inverse of 2 is 3, as 2 × 3 = 1.
3812 /// let r = two.invert_ref(&five).unwrap();
3813 /// let inverse = Integer::from(r);
3814 /// assert_eq!(inverse, 3);
3815 /// ```
3816 ///
3817 /// [icv]: crate#incomplete-computation-values
3818 pub fn invert_ref<'a>(&'a self, modulo: &'a Self) -> Option<InvertIncomplete<'a>> {
3819 xmpz::start_invert(self, modulo).map(|sinverse| InvertIncomplete { sinverse, modulo })
3820 }
3821
3822 /// Raises a number to the power of `exponent` modulo `modulo` and returns
3823 /// [`Ok(power)`][Ok] if an answer exists, or [`Err(unchanged)`][Err] if it
3824 /// does not.
3825 ///
3826 /// If the exponent is negative, then the number must have an inverse for an
3827 /// answer to exist.
3828 ///
3829 /// When the exponent is positive and the modulo is not zero, an answer
3830 /// always exists.
3831 ///
3832 /// # Examples
3833 ///
3834 /// ```rust
3835 /// use rug::Integer;
3836 /// // 7 ^ 5 = 16807
3837 /// let n = Integer::from(7);
3838 /// let e = Integer::from(5);
3839 /// let m = Integer::from(1000);
3840 /// let power = match n.pow_mod(&e, &m) {
3841 /// Ok(power) => power,
3842 /// Err(_) => unreachable!(),
3843 /// };
3844 /// assert_eq!(power, 807);
3845 /// ```
3846 ///
3847 /// When the exponent is negative, an answer exists if an inverse exists.
3848 ///
3849 /// ```rust
3850 /// use rug::Integer;
3851 /// // 7 × 143 modulo 1000 = 1, so 7 has an inverse 143.
3852 /// // 7 ^ -5 modulo 1000 = 143 ^ 5 modulo 1000 = 943.
3853 /// let n = Integer::from(7);
3854 /// let e = Integer::from(-5);
3855 /// let m = Integer::from(1000);
3856 /// let power = match n.pow_mod(&e, &m) {
3857 /// Ok(power) => power,
3858 /// Err(_) => unreachable!(),
3859 /// };
3860 /// assert_eq!(power, 943);
3861 /// ```
3862 #[inline]
3863 pub fn pow_mod(mut self, exponent: &Self, modulo: &Self) -> Result<Self, Self> {
3864 match self.pow_mod_mut(exponent, modulo) {
3865 Ok(()) => Ok(self),
3866 Err(()) => Err(self),
3867 }
3868 }
3869
3870 /// Raises a number to the power of `exponent` modulo `modulo` if an answer
3871 /// exists.
3872 ///
3873 /// If the exponent is negative, then the number must have an inverse for an
3874 /// answer to exist.
3875 ///
3876 /// # Examples
3877 ///
3878 /// ```rust
3879 /// use rug::{Assign, Integer};
3880 /// // Modulo 1000, 2 has no inverse: there is no i such that 2 × i = 1.
3881 /// let mut n = Integer::from(2);
3882 /// let e = Integer::from(-5);
3883 /// let m = Integer::from(1000);
3884 /// match n.pow_mod_mut(&e, &m) {
3885 /// Ok(()) => unreachable!(),
3886 /// Err(()) => assert_eq!(n, 2),
3887 /// }
3888 /// // 7 × 143 modulo 1000 = 1, so 7 has an inverse 143.
3889 /// // 7 ^ -5 modulo 1000 = 143 ^ 5 modulo 1000 = 943.
3890 /// n.assign(7);
3891 /// match n.pow_mod_mut(&e, &m) {
3892 /// Ok(()) => assert_eq!(n, 943),
3893 /// Err(()) => unreachable!(),
3894 /// }
3895 /// ```
3896 #[inline]
3897 #[allow(clippy::result_unit_err)]
3898 pub fn pow_mod_mut(&mut self, exponent: &Self, modulo: &Self) -> Result<(), ()> {
3899 let Some(PowModIncomplete { sinverse, .. }) = self.pow_mod_ref(exponent, modulo) else {
3900 return Err(());
3901 };
3902 if let Some(sinverse) = &sinverse {
3903 xmpz::pow_mod(self, sinverse, exponent, modulo);
3904 } else {
3905 xmpz::pow_mod(self, (), exponent, modulo);
3906 }
3907 Ok(())
3908 }
3909
3910 /// Raises a number to the power of `exponent` modulo `modulo` if an answer
3911 /// exists.
3912 ///
3913 /// If the exponent is negative, then the number must have an inverse for an
3914 /// answer to exist.
3915 ///
3916 /// The following are implemented with the unwrapped returned
3917 /// [incomplete-computation value][icv] as `Src`:
3918 /// * <code>[Assign]\<Src> for [Integer]</code>
3919 /// * <code>[From]\<Src> for [Integer]</code>
3920 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
3921 ///
3922 /// # Examples
3923 ///
3924 /// ```rust
3925 /// use rug::Integer;
3926 /// let two = Integer::from(2);
3927 /// let thousand = Integer::from(1000);
3928 /// let minus_five = Integer::from(-5);
3929 /// let seven = Integer::from(7);
3930 ///
3931 /// // Modulo 1000, 2 has no inverse: there is no i such that 2 × i = 1.
3932 /// assert!(two.pow_mod_ref(&minus_five, &thousand).is_none());
3933 ///
3934 /// // 7 × 143 modulo 1000 = 1, so 7 has an inverse 143.
3935 /// // 7 ^ -5 modulo 1000 = 143 ^ 5 modulo 1000 = 943.
3936 /// let r = seven.pow_mod_ref(&minus_five, &thousand).unwrap();
3937 /// let power = Integer::from(r);
3938 /// assert_eq!(power, 943);
3939 /// ```
3940 ///
3941 /// [icv]: crate#incomplete-computation-values
3942 pub fn pow_mod_ref<'a>(
3943 &'a self,
3944 exponent: &'a Self,
3945 modulo: &'a Self,
3946 ) -> Option<PowModIncomplete<'a>> {
3947 if exponent.is_negative() {
3948 let InvertIncomplete { sinverse, .. } = self.invert_ref(modulo)?;
3949 Some(PowModIncomplete {
3950 ref_self: None,
3951 sinverse: Some(sinverse),
3952 exponent,
3953 modulo,
3954 })
3955 } else if !modulo.is_zero() {
3956 Some(PowModIncomplete {
3957 ref_self: Some(self),
3958 sinverse: None,
3959 exponent,
3960 modulo,
3961 })
3962 } else {
3963 None
3964 }
3965 }
3966
3967 /// Raises a number to the power of `exponent` modulo `modulo`, with
3968 /// resilience to side-channel attacks.
3969 ///
3970 /// The exponent must be greater than zero, and the modulo must be odd.
3971 ///
3972 /// This method is intended for cryptographic purposes where resilience to
3973 /// side-channel attacks is desired. The function is designed to take the
3974 /// same time and use the same cache access patterns for same-sized
3975 /// arguments, assuming that the arguments are placed at the same position
3976 /// and the machine state is identical when starting.
3977 ///
3978 /// # Panics
3979 ///
3980 /// Panics if `exponent` ≤ 0 or if `modulo` is even.
3981 ///
3982 /// # Examples
3983 ///
3984 /// ```rust
3985 /// # // wrap in fn to suppress valgrind false positive
3986 /// # fn doctest_secure_pow_mod() {
3987 /// use rug::Integer;
3988 /// // 7 ^ 4 mod 13 = 9
3989 /// let n = Integer::from(7);
3990 /// let e = Integer::from(4);
3991 /// let m = Integer::from(13);
3992 /// let power = n.secure_pow_mod(&e, &m);
3993 /// assert_eq!(power, 9);
3994 /// # }
3995 /// # doctest_secure_pow_mod();
3996 /// ```
3997 #[inline]
3998 #[must_use]
3999 pub fn secure_pow_mod(mut self, exponent: &Self, modulo: &Self) -> Self {
4000 self.secure_pow_mod_mut(exponent, modulo);
4001 self
4002 }
4003
4004 /// Raises a number to the power of `exponent` modulo `modulo`, with
4005 /// resilience to side-channel attacks.
4006 ///
4007 /// The exponent must be greater than zero, and the modulo must be odd.
4008 ///
4009 /// This method is intended for cryptographic purposes where resilience to
4010 /// side-channel attacks is desired. The function is designed to take the
4011 /// same time and use the same cache access patterns for same-sized
4012 /// arguments, assuming that the arguments are placed at the same position
4013 /// and the machine state is identical when starting.
4014 ///
4015 /// # Panics
4016 ///
4017 /// Panics if `exponent` ≤ 0 or if `modulo` is even.
4018 ///
4019 /// # Examples
4020 ///
4021 /// ```rust
4022 /// # // wrap in fn to suppress valgrind false positive
4023 /// # fn doctest_secure_pow_mod_mut() {
4024 /// use rug::Integer;
4025 /// // 7 ^ 4 mod 13 = 9
4026 /// let mut n = Integer::from(7);
4027 /// let e = Integer::from(4);
4028 /// let m = Integer::from(13);
4029 /// n.secure_pow_mod_mut(&e, &m);
4030 /// assert_eq!(n, 9);
4031 /// # }
4032 /// # doctest_secure_pow_mod_mut();
4033 /// ```
4034 #[inline]
4035 pub fn secure_pow_mod_mut(&mut self, exponent: &Self, modulo: &Self) {
4036 xmpz::powm_sec(self, (), exponent, modulo);
4037 }
4038
4039 /// Raises a number to the power of `exponent` modulo `modulo`, with
4040 /// resilience to side-channel attacks.
4041 ///
4042 /// The exponent must be greater than zero, and the modulo must be odd.
4043 ///
4044 /// This method is intended for cryptographic purposes where resilience to
4045 /// side-channel attacks is desired. The function is designed to take the
4046 /// same time and use the same cache access patterns for same-sized
4047 /// arguments, assuming that the arguments are placed at the same position
4048 /// and the machine state is identical when starting.
4049 ///
4050 /// The following are implemented with the returned [incomplete-computation
4051 /// value][icv] as `Src`:
4052 /// * <code>[Assign]\<Src> for [Integer]</code>
4053 /// * <code>[From]\<Src> for [Integer]</code>
4054 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
4055 ///
4056 /// # Panics
4057 ///
4058 /// Panics if `exponent` ≤ 0 or if `modulo` is even.
4059 ///
4060 /// # Examples
4061 ///
4062 /// ```rust
4063 /// # // wrap in fn to suppress valgrind false positive
4064 /// # fn doctest_secure_pow_mod_ref() {
4065 /// use rug::Integer;
4066 /// // 7 ^ 4 mod 13 = 9
4067 /// let n = Integer::from(7);
4068 /// let e = Integer::from(4);
4069 /// let m = Integer::from(13);
4070 /// let power = Integer::from(n.secure_pow_mod_ref(&e, &m));
4071 /// assert_eq!(power, 9);
4072 /// # }
4073 /// # doctest_secure_pow_mod_ref();
4074 /// ```
4075 ///
4076 /// [icv]: crate#incomplete-computation-values
4077 #[inline]
4078 pub fn secure_pow_mod_ref<'a>(
4079 &'a self,
4080 exponent: &'a Self,
4081 modulo: &'a Self,
4082 ) -> SecurePowModIncomplete<'a> {
4083 SecurePowModIncomplete {
4084 ref_self: self,
4085 exponent,
4086 modulo,
4087 }
4088 }
4089
4090 /// Raises `base` to the power of `exponent`.
4091 ///
4092 /// The following are implemented with the returned [incomplete-computation
4093 /// value][icv] as `Src`:
4094 /// * <code>[Assign]\<Src> for [Integer]</code>
4095 /// * <code>[From]\<Src> for [Integer]</code>
4096 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
4097 ///
4098 /// # Examples
4099 ///
4100 /// ```rust
4101 /// use rug::{Complete, Integer};
4102 /// assert_eq!(Integer::u_pow_u(13, 12).complete(), 13_u64.pow(12));
4103 /// ```
4104 ///
4105 /// [icv]: crate#incomplete-computation-values
4106 #[inline]
4107 pub fn u_pow_u(base: u32, exponent: u32) -> UPowUIncomplete {
4108 UPowUIncomplete { base, exponent }
4109 }
4110
4111 /// Raises `base` to the power of `exponent`.
4112 ///
4113 /// The following are implemented with the returned [incomplete-computation
4114 /// value][icv] as `Src`:
4115 /// * <code>[Assign]\<Src> for [Integer]</code>
4116 /// * <code>[From]\<Src> for [Integer]</code>
4117 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
4118 ///
4119 /// # Examples
4120 ///
4121 /// ```rust
4122 /// use rug::{Assign, Integer};
4123 /// let mut ans = Integer::new();
4124 /// ans.assign(Integer::i_pow_u(-13, 13));
4125 /// assert_eq!(ans, (-13_i64).pow(13));
4126 /// ans.assign(Integer::i_pow_u(13, 13));
4127 /// assert_eq!(ans, (13_i64).pow(13));
4128 /// ```
4129 ///
4130 /// [icv]: crate#incomplete-computation-values
4131 #[inline]
4132 pub fn i_pow_u(base: i32, exponent: u32) -> IPowUIncomplete {
4133 IPowUIncomplete { base, exponent }
4134 }
4135
4136 /// Computes the <i>n</i>th root and truncates the result.
4137 ///
4138 /// # Panics
4139 ///
4140 /// Panics if <i>n</i> is zero or if <i>n</i> is even and the value is
4141 /// negative.
4142 ///
4143 /// # Examples
4144 ///
4145 /// ```rust
4146 /// use rug::Integer;
4147 /// let i = Integer::from(1004);
4148 /// let root = i.root(3);
4149 /// assert_eq!(root, 10);
4150 /// ```
4151 #[inline]
4152 #[must_use]
4153 pub fn root(mut self, n: u32) -> Self {
4154 self.root_mut(n);
4155 self
4156 }
4157
4158 /// Computes the <i>n</i>th root and truncates the result.
4159 ///
4160 /// # Panics
4161 ///
4162 /// Panics if <i>n</i> is zero or if <i>n</i> is even and the value is
4163 /// negative.
4164 ///
4165 /// # Examples
4166 ///
4167 /// ```rust
4168 /// use rug::Integer;
4169 /// let mut i = Integer::from(1004);
4170 /// i.root_mut(3);
4171 /// assert_eq!(i, 10);
4172 /// ```
4173 #[inline]
4174 pub fn root_mut(&mut self, n: u32) {
4175 xmpz::root(self, (), n.into());
4176 }
4177
4178 /// Computes the <i>n</i>th root and truncates the result.
4179 ///
4180 /// The following are implemented with the returned [incomplete-computation
4181 /// value][icv] as `Src`:
4182 /// * <code>[Assign]\<Src> for [Integer]</code>
4183 /// * <code>[From]\<Src> for [Integer]</code>
4184 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
4185 ///
4186 /// # Examples
4187 ///
4188 /// ```rust
4189 /// use rug::Integer;
4190 /// let i = Integer::from(1004);
4191 /// assert_eq!(Integer::from(i.root_ref(3)), 10);
4192 /// ```
4193 ///
4194 /// [icv]: crate#incomplete-computation-values
4195 #[inline]
4196 pub fn root_ref(&self, n: u32) -> RootIncomplete<'_> {
4197 let n = n.into();
4198 RootIncomplete { ref_self: self, n }
4199 }
4200
4201 /// Computes the <i>n</i>th root and returns the truncated root and the
4202 /// remainder.
4203 ///
4204 /// The remainder is the original number minus the truncated root raised to
4205 /// the power of <i>n</i>.
4206 ///
4207 /// The initial value of `remainder` is ignored.
4208 ///
4209 /// # Panics
4210 ///
4211 /// Panics if <i>n</i> is zero or if <i>n</i> is even and the value is
4212 /// negative.
4213 ///
4214 /// # Examples
4215 ///
4216 /// ```rust
4217 /// use rug::Integer;
4218 /// let i = Integer::from(1004);
4219 /// let (root, rem) = i.root_rem(Integer::new(), 3);
4220 /// assert_eq!(root, 10);
4221 /// assert_eq!(rem, 4);
4222 /// ```
4223 #[inline]
4224 pub fn root_rem(mut self, mut remainder: Self, n: u32) -> (Self, Self) {
4225 self.root_rem_mut(&mut remainder, n);
4226 (self, remainder)
4227 }
4228
4229 /// Computes the <i>n</i>th root and returns the truncated root and the
4230 /// remainder.
4231 ///
4232 /// The remainder is the original number minus the truncated root raised to
4233 /// the power of <i>n</i>.
4234 ///
4235 /// The initial value of `remainder` is ignored.
4236 ///
4237 /// # Panics
4238 ///
4239 /// Panics if <i>n</i> is zero or if <i>n</i> is even and the value is
4240 /// negative.
4241 ///
4242 /// # Examples
4243 ///
4244 /// ```rust
4245 /// use rug::Integer;
4246 /// let mut i = Integer::from(1004);
4247 /// let mut rem = Integer::new();
4248 /// i.root_rem_mut(&mut rem, 3);
4249 /// assert_eq!(i, 10);
4250 /// assert_eq!(rem, 4);
4251 /// ```
4252 #[inline]
4253 pub fn root_rem_mut(&mut self, remainder: &mut Self, n: u32) {
4254 xmpz::rootrem(self, remainder, (), n.into());
4255 }
4256
4257 /// Computes the <i>n</i>th root and returns the truncated root and the
4258 /// remainder.
4259 ///
4260 /// The remainder is the original number minus the truncated root raised to
4261 /// the power of <i>n</i>.
4262 ///
4263 /// The following are implemented with the returned [incomplete-computation
4264 /// value][icv] as `Src`:
4265 /// * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
4266 /// * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
4267 /// * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
4268 /// * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
4269 ///
4270 /// # Examples
4271 ///
4272 /// ```rust
4273 /// use rug::{Assign, Complete, Integer};
4274 /// let i = Integer::from(1004);
4275 /// let mut root = Integer::new();
4276 /// let mut rem = Integer::new();
4277 /// // 1004 = 10^3 + 5
4278 /// (&mut root, &mut rem).assign(i.root_rem_ref(3));
4279 /// assert_eq!(root, 10);
4280 /// assert_eq!(rem, 4);
4281 /// // 1004 = 3^6 + 275
4282 /// let (other_root, other_rem) = i.root_rem_ref(6).complete();
4283 /// assert_eq!(other_root, 3);
4284 /// assert_eq!(other_rem, 275);
4285 /// ```
4286 ///
4287 /// [icv]: crate#incomplete-computation-values
4288 #[inline]
4289 pub fn root_rem_ref(&self, n: u32) -> RootRemIncomplete<'_> {
4290 let n = n.into();
4291 RootRemIncomplete { ref_self: self, n }
4292 }
4293
4294 /// Computes the square.
4295 ///
4296 /// This method cannot be replaced by a multiplication using the `*`
4297 /// operator: `i * i` and `i * &i` are both errors.
4298 ///
4299 /// # Examples
4300 ///
4301 /// ```rust
4302 /// use rug::Integer;
4303 /// let i = Integer::from(13);
4304 /// let square = i.square();
4305 /// assert_eq!(square, 169);
4306 /// ```
4307 #[inline]
4308 #[must_use]
4309 pub fn square(mut self) -> Self {
4310 self.square_mut();
4311 self
4312 }
4313
4314 /// Computes the square.
4315 ///
4316 /// This method cannot be replaced by a compound multiplication and
4317 /// assignment using the `*=` operataor: `i *= i;` and `i *= &i;` are both
4318 /// errors.
4319 ///
4320 /// # Examples
4321 ///
4322 /// ```rust
4323 /// use rug::Integer;
4324 /// let mut i = Integer::from(13);
4325 /// i.square_mut();
4326 /// assert_eq!(i, 169);
4327 /// ```
4328 #[inline]
4329 pub fn square_mut(&mut self) {
4330 xmpz::mul(self, (), ());
4331 }
4332
4333 /// Computes the square.
4334 ///
4335 /// The following are implemented with the returned [incomplete-computation
4336 /// value][icv] as `Src`:
4337 /// * <code>[Assign]\<Src> for [Integer]</code>
4338 /// * <code>[From]\<Src> for [Integer]</code>
4339 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
4340 /// * <code>[AddAssign]\<Src> for [Integer]</code>
4341 /// * <code>[Add]\<Src> for [Integer]</code>,
4342 /// <code>[Add]\<[Integer]> for Src</code>
4343 /// * <code>[SubAssign]\<Src> for [Integer]</code>,
4344 /// <code>[SubFrom]\<Src> for [Integer]</code>
4345 /// * <code>[Sub]\<Src> for [Integer]</code>,
4346 /// <code>[Sub]\<[Integer]> for Src</code>
4347 ///
4348 /// `i.square_ref()` produces the exact same result as `&i * &i`.
4349 ///
4350 /// # Examples
4351 ///
4352 /// ```rust
4353 /// use rug::Integer;
4354 /// let i = Integer::from(13);
4355 /// assert_eq!(Integer::from(i.square_ref()), 169);
4356 /// ```
4357 ///
4358 /// [icv]: crate#incomplete-computation-values
4359 #[inline]
4360 pub fn square_ref(&self) -> MulIncomplete<'_> {
4361 self * self
4362 }
4363
4364 /// Computes the square root and truncates the result.
4365 ///
4366 /// # Panics
4367 ///
4368 /// Panics if the value is negative.
4369 ///
4370 /// # Examples
4371 ///
4372 /// ```rust
4373 /// use rug::Integer;
4374 /// let i = Integer::from(104);
4375 /// let sqrt = i.sqrt();
4376 /// assert_eq!(sqrt, 10);
4377 /// ```
4378 #[inline]
4379 #[must_use]
4380 pub fn sqrt(mut self) -> Self {
4381 self.sqrt_mut();
4382 self
4383 }
4384
4385 /// Computes the square root and truncates the result.
4386 ///
4387 /// # Panics
4388 ///
4389 /// Panics if the value is negative.
4390 ///
4391 /// # Examples
4392 ///
4393 /// ```rust
4394 /// use rug::Integer;
4395 /// let mut i = Integer::from(104);
4396 /// i.sqrt_mut();
4397 /// assert_eq!(i, 10);
4398 /// ```
4399 #[inline]
4400 pub fn sqrt_mut(&mut self) {
4401 xmpz::sqrt(self, ());
4402 }
4403
4404 /// Computes the square root and truncates the result.
4405 ///
4406 /// The following are implemented with the returned [incomplete-computation
4407 /// value][icv] as `Src`:
4408 /// * <code>[Assign]\<Src> for [Integer]</code>
4409 /// * <code>[From]\<Src> for [Integer]</code>
4410 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
4411 ///
4412 /// # Examples
4413 ///
4414 /// ```rust
4415 /// use rug::Integer;
4416 /// let i = Integer::from(104);
4417 /// assert_eq!(Integer::from(i.sqrt_ref()), 10);
4418 /// ```
4419 ///
4420 /// [icv]: crate#incomplete-computation-values
4421 #[inline]
4422 pub fn sqrt_ref(&self) -> SqrtIncomplete<'_> {
4423 SqrtIncomplete { ref_self: self }
4424 }
4425
4426 /// Computes the square root and the remainder.
4427 ///
4428 /// The remainder is the original number minus the truncated root squared.
4429 ///
4430 /// The initial value of `remainder` is ignored.
4431 ///
4432 /// # Panics
4433 ///
4434 /// Panics if the value is negative.
4435 ///
4436 /// # Examples
4437 ///
4438 /// ```rust
4439 /// use rug::Integer;
4440 /// let i = Integer::from(104);
4441 /// let (sqrt, rem) = i.sqrt_rem(Integer::new());
4442 /// assert_eq!(sqrt, 10);
4443 /// assert_eq!(rem, 4);
4444 /// ```
4445 #[inline]
4446 pub fn sqrt_rem(mut self, mut remainder: Self) -> (Self, Self) {
4447 self.sqrt_rem_mut(&mut remainder);
4448 (self, remainder)
4449 }
4450
4451 /// Computes the square root and the remainder.
4452 ///
4453 /// The remainder is the original number minus the truncated root squared.
4454 ///
4455 /// The initial value of `remainder` is ignored.
4456 ///
4457 /// # Panics
4458 ///
4459 /// Panics if the value is negative.
4460 ///
4461 /// # Examples
4462 ///
4463 /// ```rust
4464 /// use rug::Integer;
4465 /// let mut i = Integer::from(104);
4466 /// let mut rem = Integer::new();
4467 /// i.sqrt_rem_mut(&mut rem);
4468 /// assert_eq!(i, 10);
4469 /// assert_eq!(rem, 4);
4470 /// ```
4471 #[inline]
4472 pub fn sqrt_rem_mut(&mut self, remainder: &mut Self) {
4473 xmpz::sqrtrem(self, remainder, ());
4474 }
4475
4476 /// Computes the square root and the remainder.
4477 ///
4478 /// The remainder is the original number minus the truncated root squared.
4479 ///
4480 /// The following are implemented with the returned [incomplete-computation
4481 /// value][icv] as `Src`:
4482 /// * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
4483 /// * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
4484 /// * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
4485 /// * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
4486 ///
4487 /// # Examples
4488 ///
4489 /// ```rust
4490 /// use rug::{Assign, Integer};
4491 /// let i = Integer::from(104);
4492 /// let mut sqrt = Integer::new();
4493 /// let mut rem = Integer::new();
4494 /// let r = i.sqrt_rem_ref();
4495 /// (&mut sqrt, &mut rem).assign(r);
4496 /// assert_eq!(sqrt, 10);
4497 /// assert_eq!(rem, 4);
4498 /// let r = i.sqrt_rem_ref();
4499 /// let (other_sqrt, other_rem) = <(Integer, Integer)>::from(r);
4500 /// assert_eq!(other_sqrt, 10);
4501 /// assert_eq!(other_rem, 4);
4502 /// ```
4503 ///
4504 /// [icv]: crate#incomplete-computation-values
4505 #[inline]
4506 pub fn sqrt_rem_ref(&self) -> SqrtRemIncomplete<'_> {
4507 SqrtRemIncomplete { ref_self: self }
4508 }
4509
4510 /// Determines wheter a number is prime.
4511 ///
4512 /// This function uses some trial divisions, a Baille-PSW probable prime
4513 /// test, then `reps` − 24 Miller-Rabin probabilistic
4514 /// primality tests.
4515 ///
4516 /// # Examples
4517 ///
4518 /// ```rust
4519 /// use rug::integer::IsPrime;
4520 /// use rug::Integer;
4521 /// let no = Integer::from(163 * 4003);
4522 /// assert_eq!(no.is_probably_prime(30), IsPrime::No);
4523 /// let yes = Integer::from(817_504_243);
4524 /// assert_eq!(yes.is_probably_prime(30), IsPrime::Yes);
4525 /// // 16_412_292_043_871_650_369 is actually a prime.
4526 /// let probably = Integer::from(16_412_292_043_871_650_369_u64);
4527 /// assert_eq!(probably.is_probably_prime(30), IsPrime::Probably);
4528 /// ```
4529 #[inline]
4530 pub fn is_probably_prime(&self, reps: u32) -> IsPrime {
4531 match xmpz::probab_prime_p(self, reps.unwrapped_cast()) {
4532 0 => IsPrime::No,
4533 1 => IsPrime::Probably,
4534 2 => IsPrime::Yes,
4535 _ => unreachable!(),
4536 }
4537 }
4538
4539 /// Identifies primes using a probabilistic algorithm; the chance of a
4540 /// composite passing will be extremely small.
4541 ///
4542 /// # Examples
4543 ///
4544 /// ```rust
4545 /// use rug::Integer;
4546 /// let i = Integer::from(800_000_000);
4547 /// let prime = i.next_prime();
4548 /// assert_eq!(prime, 800_000_011);
4549 /// ```
4550 #[inline]
4551 #[must_use]
4552 pub fn next_prime(mut self) -> Self {
4553 self.next_prime_mut();
4554 self
4555 }
4556
4557 /// Identifies primes using a probabilistic algorithm; the chance of a
4558 /// composite passing will be extremely small.
4559 ///
4560 /// # Examples
4561 ///
4562 /// ```rust
4563 /// use rug::Integer;
4564 /// let mut i = Integer::from(800_000_000);
4565 /// i.next_prime_mut();
4566 /// assert_eq!(i, 800_000_011);
4567 /// ```
4568 #[inline]
4569 pub fn next_prime_mut(&mut self) {
4570 xmpz::nextprime(self, ());
4571 }
4572
4573 /// Identifies primes using a probabilistic algorithm; the chance of a
4574 /// composite passing will be extremely small.
4575 ///
4576 /// The following are implemented with the returned [incomplete-computation
4577 /// value][icv] as `Src`:
4578 /// * <code>[Assign]\<Src> for [Integer]</code>
4579 /// * <code>[From]\<Src> for [Integer]</code>
4580 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
4581 ///
4582 /// # Examples
4583 ///
4584 /// ```rust
4585 /// use rug::Integer;
4586 /// let i = Integer::from(800_000_000);
4587 /// let r = i.next_prime_ref();
4588 /// let prime = Integer::from(r);
4589 /// assert_eq!(prime, 800_000_011);
4590 /// ```
4591 ///
4592 /// [icv]: crate#incomplete-computation-values
4593 #[inline]
4594 pub fn next_prime_ref(&self) -> NextPrimeIncomplete<'_> {
4595 NextPrimeIncomplete { ref_self: self }
4596 }
4597
4598 /// Identifies previous prime number using a probabilistic algorithm; the
4599 /// chance of a composite passing will be extremely small.
4600 ///
4601 /// # Examples
4602 ///
4603 /// ```rust
4604 /// use rug::Integer;
4605 /// let i = Integer::from(800_000_000);
4606 /// let prime = i.prev_prime();
4607 /// assert_eq!(prime, 799_999_999);
4608 /// ```
4609 #[inline]
4610 #[must_use]
4611 pub fn prev_prime(mut self) -> Self {
4612 self.prev_prime_mut();
4613 self
4614 }
4615
4616 /// Identifies previous prime number using a probabilistic algorithm; the
4617 /// chance of a composite passing will be extremely small.
4618 ///
4619 /// # Examples
4620 ///
4621 /// ```rust
4622 /// use rug::Integer;
4623 /// let mut i = Integer::from(800_000_000);
4624 /// i.prev_prime_mut();
4625 /// assert_eq!(i, 799_999_999);
4626 /// ```
4627 #[inline]
4628 pub fn prev_prime_mut(&mut self) {
4629 xmpz::prevprime(self, ());
4630 }
4631
4632 /// Identifies previous prime number using a probabilistic algorithm; the
4633 /// chance of a composite passing will be extremely small.
4634 ///
4635 /// The following are implemented with the returned [incomplete-computation
4636 /// value][icv] as `Src`:
4637 /// * <code>[Assign]\<Src> for [Integer]</code>
4638 /// * <code>[From]\<Src> for [Integer]</code>
4639 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
4640 ///
4641 /// # Examples
4642 ///
4643 /// ```rust
4644 /// use rug::Integer;
4645 /// let i = Integer::from(800_000_000);
4646 /// let r = i.prev_prime_ref();
4647 /// let prime = Integer::from(r);
4648 /// assert_eq!(prime, 799_999_999);
4649 /// ```
4650 ///
4651 /// [icv]: crate#incomplete-computation-values
4652 #[inline]
4653 pub fn prev_prime_ref(&self) -> PrevPrimeIncomplete<'_> {
4654 PrevPrimeIncomplete { ref_self: self }
4655 }
4656
4657 /// Finds the greatest common divisor.
4658 ///
4659 /// The result is always positive except when both inputs are zero.
4660 ///
4661 /// # Examples
4662 ///
4663 /// ```rust
4664 /// use rug::{Assign, Integer};
4665 /// let a = Integer::new();
4666 /// let mut b = Integer::new();
4667 /// // gcd of 0, 0 is 0
4668 /// let gcd1 = a.gcd(&b);
4669 /// assert_eq!(gcd1, 0);
4670 /// b.assign(10);
4671 /// // gcd of 0, 10 is 10
4672 /// let gcd2 = gcd1.gcd(&b);
4673 /// assert_eq!(gcd2, 10);
4674 /// b.assign(25);
4675 /// // gcd of 10, 25 is 5
4676 /// let gcd3 = gcd2.gcd(&b);
4677 /// assert_eq!(gcd3, 5);
4678 /// ```
4679 #[inline]
4680 #[must_use]
4681 pub fn gcd(mut self, other: &Self) -> Self {
4682 self.gcd_mut(other);
4683 self
4684 }
4685
4686 /// Finds the greatest common divisor.
4687 ///
4688 /// The result is always positive except when both inputs are zero.
4689 ///
4690 /// # Examples
4691 ///
4692 /// ```rust
4693 /// use rug::{Assign, Integer};
4694 /// let mut a = Integer::new();
4695 /// let mut b = Integer::new();
4696 /// // gcd of 0, 0 is 0
4697 /// a.gcd_mut(&b);
4698 /// assert_eq!(a, 0);
4699 /// b.assign(10);
4700 /// // gcd of 0, 10 is 10
4701 /// a.gcd_mut(&b);
4702 /// assert_eq!(a, 10);
4703 /// b.assign(25);
4704 /// // gcd of 10, 25 is 5
4705 /// a.gcd_mut(&b);
4706 /// assert_eq!(a, 5);
4707 /// ```
4708 #[inline]
4709 pub fn gcd_mut(&mut self, other: &Self) {
4710 xmpz::gcd(self, (), other);
4711 }
4712
4713 /// Finds the greatest common divisor.
4714 ///
4715 /// The result is always positive except when both inputs are zero.
4716 ///
4717 /// The following are implemented with the returned [incomplete-computation
4718 /// value][icv] as `Src`:
4719 /// * <code>[Assign]\<Src> for [Integer]</code>
4720 /// * <code>[From]\<Src> for [Integer]</code>
4721 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
4722 ///
4723 /// # Examples
4724 ///
4725 /// ```rust
4726 /// use rug::Integer;
4727 /// let a = Integer::from(100);
4728 /// let b = Integer::from(125);
4729 /// let r = a.gcd_ref(&b);
4730 /// // gcd of 100, 125 is 25
4731 /// assert_eq!(Integer::from(r), 25);
4732 /// ```
4733 ///
4734 /// [icv]: crate#incomplete-computation-values
4735 #[inline]
4736 pub fn gcd_ref<'a>(&'a self, other: &'a Self) -> GcdIncomplete<'a> {
4737 GcdIncomplete {
4738 ref_self: self,
4739 other,
4740 }
4741 }
4742
4743 /// Finds the greatest common divisor.
4744 ///
4745 /// The result is always positive except when both inputs are zero.
4746 ///
4747 /// # Examples
4748 ///
4749 /// ```rust
4750 /// use rug::Integer;
4751 /// let i = Integer::new();
4752 /// // gcd of 0, 0 is 0
4753 /// let gcd1 = i.gcd_u(0);
4754 /// assert_eq!(gcd1, 0);
4755 /// // gcd of 0, 10 is 10
4756 /// let gcd2 = gcd1.gcd_u(10);
4757 /// assert_eq!(gcd2, 10);
4758 /// // gcd of 10, 25 is 5
4759 /// let gcd3 = gcd2.gcd_u(25);
4760 /// assert_eq!(gcd3, 5);
4761 /// ```
4762 #[inline]
4763 #[must_use]
4764 pub fn gcd_u(mut self, other: u32) -> Self {
4765 self.gcd_u_mut(other);
4766 self
4767 }
4768
4769 /// Finds the greatest common divisor.
4770 ///
4771 /// The result is always positive except when both inputs are zero.
4772 ///
4773 /// # Examples
4774 ///
4775 /// ```rust
4776 /// use rug::Integer;
4777 /// let mut i = Integer::new();
4778 /// // gcd of 0, 0 is 0
4779 /// i.gcd_u_mut(0);
4780 /// assert_eq!(i, 0);
4781 /// // gcd of 0, 10 is 10
4782 /// i.gcd_u_mut(10);
4783 /// assert_eq!(i, 10);
4784 /// // gcd of 10, 25 is 5
4785 /// i.gcd_u_mut(25);
4786 /// assert_eq!(i, 5);
4787 /// ```
4788 #[inline]
4789 pub fn gcd_u_mut(&mut self, other: u32) {
4790 xmpz::gcd_ui(self, (), other.into());
4791 }
4792
4793 /// Finds the greatest common divisor.
4794 ///
4795 /// The result is always positive except when both inputs are zero.
4796 ///
4797 /// The following are implemented with the returned [incomplete-computation
4798 /// value][icv] as `Src`:
4799 /// * <code>[Assign]\<Src> for [Integer]</code>
4800 /// * <code>[From]\<Src> for [Integer]</code>
4801 /// * <code>[From]\<Src> for [Option]\<[u32]></code>
4802 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
4803 ///
4804 /// The implementation of <code>[From]\<Src> for [Option]\<[u32]></code> is
4805 /// useful to obtain the result as a [`u32`] if it fits. If
4806 /// `other` > 0 , the result always fits. If the result does not
4807 /// fit, it is equal to the absolute value of `self`.
4808 ///
4809 /// # Examples
4810 ///
4811 /// ```rust
4812 /// use rug::Integer;
4813 /// let i = Integer::from(100);
4814 /// let r = i.gcd_u_ref(125);
4815 /// // gcd of 100, 125 is 25
4816 /// assert_eq!(Integer::from(r), 25);
4817 /// let r = i.gcd_u_ref(125);
4818 /// assert_eq!(Option::<u32>::from(r), Some(25));
4819 /// ```
4820 ///
4821 /// [icv]: crate#incomplete-computation-values
4822 #[inline]
4823 pub fn gcd_u_ref(&self, other: u32) -> GcdUIncomplete<'_> {
4824 let other = other.into();
4825 GcdUIncomplete {
4826 ref_self: self,
4827 other,
4828 }
4829 }
4830
4831 /// Finds the greatest common divisor (GCD) of the two inputs (`self` and
4832 /// `other`), and two coefficients to obtain the GCD from the two inputs.
4833 ///
4834 /// The GCD is always positive except when both inputs are zero. If the
4835 /// inputs are <i>a</i> and <i>b</i>, then the GCD is <i>g</i> and the
4836 /// coefficients are <i>s</i> and <i>t</i> such that
4837 ///
4838 /// <i>a</i> × <i>s</i> + <i>b</i> × <i>t</i> = <i>g</i>
4839 ///
4840 /// The values <i>s</i> and <i>t</i> are chosen such that normally,
4841 /// |<i>s</i>| < |<i>b</i>| / (2<i>g</i>) and
4842 /// |<i>t</i>| < |<i>a</i>| / (2<i>g</i>), and these
4843 /// relations define <i>s</i> and <i>t</i> uniquely. There are a few
4844 /// exceptional cases:
4845 ///
4846 /// * If |<i>a</i>| = |<i>b</i>|, then <i>s</i> = 0,
4847 /// <i>t</i> = sgn(<i>b</i>).
4848 /// * Otherwise, if <i>b</i> = 0 or
4849 /// |<i>b</i>| = 2<i>g</i>, then
4850 /// <i>s</i> = sgn(<i>a</i>), and if <i>a</i> = 0 or
4851 /// |<i>a</i>| = 2<i>g</i>, then
4852 /// <i>t</i> = sgn(<i>b</i>).
4853 ///
4854 /// The initial value of `rop` is ignored.
4855 ///
4856 /// # Examples
4857 ///
4858 /// ```rust
4859 /// use rug::Integer;
4860 /// let a = Integer::from(4);
4861 /// let b = Integer::from(6);
4862 /// let (g, s, t) = a.extended_gcd(b, Integer::new());
4863 /// assert_eq!(g, 2);
4864 /// assert_eq!(s, -1);
4865 /// assert_eq!(t, 1);
4866 /// ```
4867 #[inline]
4868 pub fn extended_gcd(mut self, mut other: Self, mut rop: Self) -> (Self, Self, Self) {
4869 self.extended_gcd_mut(&mut other, &mut rop);
4870 (self, other, rop)
4871 }
4872
4873 /// Finds the greatest common divisor (GCD) of the two inputs (`self` and
4874 /// `other`), and two coefficients to obtain the GCD from the two inputs.
4875 ///
4876 /// The GCD is stored in `self`, and the two coefficients are stored in
4877 /// `other` and `rop`.
4878 ///
4879 /// The GCD is always positive except when both inputs are zero. If the
4880 /// inputs are <i>a</i> and <i>b</i>, then the GCD is <i>g</i> and the
4881 /// coefficients are <i>s</i> and <i>t</i> such that
4882 ///
4883 /// <i>a</i> × <i>s</i> + <i>b</i> × <i>t</i> = <i>g</i>
4884 ///
4885 /// The values <i>s</i> and <i>t</i> are chosen such that normally,
4886 /// |<i>s</i>| < |<i>b</i>| / (2<i>g</i>) and
4887 /// |<i>t</i>| < |<i>a</i>| / (2<i>g</i>), and these
4888 /// relations define <i>s</i> and <i>t</i> uniquely. There are a few
4889 /// exceptional cases:
4890 ///
4891 /// * If |<i>a</i>| = |<i>b</i>|, then <i>s</i> = 0,
4892 /// <i>t</i> = sgn(<i>b</i>).
4893 /// * Otherwise, if <i>b</i> = 0 or
4894 /// |<i>b</i>| = 2<i>g</i>, then
4895 /// <i>s</i> = sgn(<i>a</i>), and if <i>a</i> = 0 or
4896 /// |<i>a</i>| = 2<i>g</i>, then
4897 /// <i>t</i> = sgn(<i>b</i>).
4898 ///
4899 /// The initial value of `rop` is ignored.
4900 ///
4901 /// # Examples
4902 ///
4903 /// ```rust
4904 /// use rug::Integer;
4905 /// let mut a_g = Integer::from(4);
4906 /// let mut b_s = Integer::from(6);
4907 /// let mut t = Integer::new();
4908 /// a_g.extended_gcd_mut(&mut b_s, &mut t);
4909 /// assert_eq!(a_g, 2);
4910 /// assert_eq!(b_s, -1);
4911 /// assert_eq!(t, 1);
4912 /// ```
4913 #[inline]
4914 pub fn extended_gcd_mut(&mut self, other: &mut Self, rop: &mut Self) {
4915 xmpz::gcdext(self, other, Some(rop), (), ());
4916 }
4917
4918 /// Finds the greatest common divisor (GCD) of the two inputs (`self` and
4919 /// `other`), and two coefficients to obtain the GCD from the two inputs.
4920 ///
4921 /// The following are implemented with the returned [incomplete-computation
4922 /// value][icv] as `Src`:
4923 /// * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer], [Integer][][)][tuple]</code>
4924 /// * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer], \&mut [Integer][][)][tuple]</code>
4925 /// * <code>[From]\<Src> for [(][tuple][Integer][], [Integer], [Integer][][)][tuple]</code>
4926 /// * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer], [Integer][][)][tuple]> for Src</code>
4927 ///
4928 /// In the case that only one of the two coefficients is required, the
4929 /// following are also implemented:
4930 /// * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
4931 /// * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
4932 /// * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
4933 ///
4934 /// The GCD is always positive except when both inputs are zero. If the
4935 /// inputs are <i>a</i> and <i>b</i>, then the GCD is <i>g</i> and the
4936 /// coefficients are <i>s</i> and <i>t</i> such that
4937 ///
4938 /// <i>a</i> × <i>s</i> + <i>b</i> × <i>t</i> = <i>g</i>
4939 ///
4940 /// The values <i>s</i> and <i>t</i> are chosen such that normally,
4941 /// |<i>s</i>| < |<i>b</i>| / (2<i>g</i>) and
4942 /// |<i>t</i>| < |<i>a</i>| / (2<i>g</i>), and these
4943 /// relations define <i>s</i> and <i>t</i> uniquely. There are a few
4944 /// exceptional cases:
4945 ///
4946 /// * If |<i>a</i>| = |<i>b</i>|, then <i>s</i> = 0,
4947 /// <i>t</i> = sgn(<i>b</i>).
4948 /// * Otherwise, if <i>b</i> = 0 or
4949 /// |<i>b</i>| = 2<i>g</i>, then
4950 /// <i>s</i> = sgn(<i>a</i>), and if <i>a</i> = 0 or
4951 /// |<i>a</i>| = 2<i>g</i>, then
4952 /// <i>t</i> = sgn(<i>b</i>).
4953 ///
4954 /// # Examples
4955 ///
4956 /// ```rust
4957 /// use rug::{Assign, Integer};
4958 /// let a = Integer::from(4);
4959 /// let b = Integer::from(6);
4960 /// let r = a.extended_gcd_ref(&b);
4961 /// let mut g = Integer::new();
4962 /// let mut s = Integer::new();
4963 /// let mut t = Integer::new();
4964 /// (&mut g, &mut s, &mut t).assign(r);
4965 /// assert_eq!(a, 4);
4966 /// assert_eq!(b, 6);
4967 /// assert_eq!(g, 2);
4968 /// assert_eq!(s, -1);
4969 /// assert_eq!(t, 1);
4970 /// ```
4971 ///
4972 /// In the case that only one of the two coefficients is required, this can
4973 /// be achieved as follows:
4974 ///
4975 /// ```rust
4976 /// use rug::{Assign, Integer};
4977 /// let a = Integer::from(4);
4978 /// let b = Integer::from(6);
4979 ///
4980 /// // no t required
4981 /// let (mut g1, mut s1) = (Integer::new(), Integer::new());
4982 /// (&mut g1, &mut s1).assign(a.extended_gcd_ref(&b));
4983 /// assert_eq!(g1, 2);
4984 /// assert_eq!(s1, -1);
4985 ///
4986 /// // no s required
4987 /// let (mut g2, mut t2) = (Integer::new(), Integer::new());
4988 /// (&mut g2, &mut t2).assign(b.extended_gcd_ref(&a));
4989 /// assert_eq!(g2, 2);
4990 /// assert_eq!(t2, 1);
4991 /// ```
4992 ///
4993 /// [icv]: crate#incomplete-computation-values
4994 #[inline]
4995 pub fn extended_gcd_ref<'a>(&'a self, other: &'a Self) -> GcdExtIncomplete<'a> {
4996 GcdExtIncomplete {
4997 ref_self: self,
4998 other,
4999 }
5000 }
5001
5002 /// Finds the least common multiple.
5003 ///
5004 /// The result is always positive except when one or both inputs are zero.
5005 ///
5006 /// # Examples
5007 ///
5008 /// ```rust
5009 /// use rug::{Assign, Integer};
5010 /// let a = Integer::from(10);
5011 /// let mut b = Integer::from(25);
5012 /// // lcm of 10, 25 is 50
5013 /// let lcm1 = a.lcm(&b);
5014 /// assert_eq!(lcm1, 50);
5015 /// b.assign(0);
5016 /// // lcm of 50, 0 is 0
5017 /// let lcm2 = lcm1.lcm(&b);
5018 /// assert_eq!(lcm2, 0);
5019 /// ```
5020 #[inline]
5021 #[must_use]
5022 pub fn lcm(mut self, other: &Self) -> Self {
5023 self.lcm_mut(other);
5024 self
5025 }
5026
5027 /// Finds the least common multiple.
5028 ///
5029 /// The result is always positive except when one or both inputs are zero.
5030 ///
5031 /// # Examples
5032 ///
5033 /// ```rust
5034 /// use rug::{Assign, Integer};
5035 /// let mut a = Integer::from(10);
5036 /// let mut b = Integer::from(25);
5037 /// // lcm of 10, 25 is 50
5038 /// a.lcm_mut(&b);
5039 /// assert_eq!(a, 50);
5040 /// b.assign(0);
5041 /// // lcm of 50, 0 is 0
5042 /// a.lcm_mut(&b);
5043 /// assert_eq!(a, 0);
5044 /// ```
5045 #[inline]
5046 pub fn lcm_mut(&mut self, other: &Self) {
5047 xmpz::lcm(self, (), other);
5048 }
5049
5050 /// Finds the least common multiple.
5051 ///
5052 /// The result is always positive except when one or both inputs are zero.
5053 ///
5054 /// The following are implemented with the returned [incomplete-computation
5055 /// value][icv] as `Src`:
5056 /// * <code>[Assign]\<Src> for [Integer]</code>
5057 /// * <code>[From]\<Src> for [Integer]</code>
5058 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5059 ///
5060 /// # Examples
5061 ///
5062 /// ```rust
5063 /// use rug::Integer;
5064 /// let a = Integer::from(100);
5065 /// let b = Integer::from(125);
5066 /// let r = a.lcm_ref(&b);
5067 /// // lcm of 100, 125 is 500
5068 /// assert_eq!(Integer::from(r), 500);
5069 /// ```
5070 ///
5071 /// [icv]: crate#incomplete-computation-values
5072 #[inline]
5073 pub fn lcm_ref<'a>(&'a self, other: &'a Self) -> LcmIncomplete<'a> {
5074 LcmIncomplete {
5075 ref_self: self,
5076 other,
5077 }
5078 }
5079
5080 /// Finds the least common multiple.
5081 ///
5082 /// The result is always positive except when one or both inputs are zero.
5083 ///
5084 /// # Examples
5085 ///
5086 /// ```rust
5087 /// use rug::Integer;
5088 /// let i = Integer::from(10);
5089 /// // lcm of 10, 25 is 50
5090 /// let lcm1 = i.lcm_u(25);
5091 /// assert_eq!(lcm1, 50);
5092 /// // lcm of 50, 0 is 0
5093 /// let lcm2 = lcm1.lcm_u(0);
5094 /// assert_eq!(lcm2, 0);
5095 /// ```
5096 #[inline]
5097 #[must_use]
5098 pub fn lcm_u(mut self, other: u32) -> Self {
5099 self.lcm_u_mut(other);
5100 self
5101 }
5102
5103 /// Finds the least common multiple.
5104 ///
5105 /// The result is always positive except when one or both inputs are zero.
5106 ///
5107 /// # Examples
5108 ///
5109 /// ```rust
5110 /// use rug::Integer;
5111 /// let mut i = Integer::from(10);
5112 /// // lcm of 10, 25 is 50
5113 /// i.lcm_u_mut(25);
5114 /// assert_eq!(i, 50);
5115 /// // lcm of 50, 0 is 0
5116 /// i.lcm_u_mut(0);
5117 /// assert_eq!(i, 0);
5118 /// ```
5119 #[inline]
5120 pub fn lcm_u_mut(&mut self, other: u32) {
5121 xmpz::lcm_ui(self, (), other.into());
5122 }
5123
5124 /// Finds the least common multiple.
5125 ///
5126 /// The result is always positive except when one or both inputs are zero.
5127 ///
5128 /// The following are implemented with the returned [incomplete-computation
5129 /// value][icv] as `Src`:
5130 /// * <code>[Assign]\<Src> for [Integer]</code>
5131 /// * <code>[From]\<Src> for [Integer]</code>
5132 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5133 ///
5134 /// # Examples
5135 ///
5136 /// ```rust
5137 /// use rug::Integer;
5138 /// let i = Integer::from(100);
5139 /// let r = i.lcm_u_ref(125);
5140 /// // lcm of 100, 125 is 500
5141 /// assert_eq!(Integer::from(r), 500);
5142 /// ```
5143 ///
5144 /// [icv]: crate#incomplete-computation-values
5145 #[inline]
5146 pub fn lcm_u_ref(&self, other: u32) -> LcmUIncomplete<'_> {
5147 let other = other.into();
5148 LcmUIncomplete {
5149 ref_self: self,
5150 other,
5151 }
5152 }
5153
5154 /// Calculates the Jacobi symbol (`self`/<i>n</i>).
5155 ///
5156 /// # Examples
5157 ///
5158 /// ```rust
5159 /// use rug::{Assign, Integer};
5160 /// let m = Integer::from(10);
5161 /// let mut n = Integer::from(13);
5162 /// assert_eq!(m.jacobi(&n), 1);
5163 /// n.assign(15);
5164 /// assert_eq!(m.jacobi(&n), 0);
5165 /// n.assign(17);
5166 /// assert_eq!(m.jacobi(&n), -1);
5167 /// ```
5168 #[inline]
5169 pub fn jacobi(&self, n: &Self) -> i32 {
5170 xmpz::jacobi(self, n).cast()
5171 }
5172
5173 /// Calculates the Legendre symbol (`self`/<i>p</i>).
5174 ///
5175 /// # Examples
5176 ///
5177 /// ```rust
5178 /// use rug::{Assign, Integer};
5179 /// let a = Integer::from(5);
5180 /// let mut p = Integer::from(7);
5181 /// assert_eq!(a.legendre(&p), -1);
5182 /// p.assign(11);
5183 /// assert_eq!(a.legendre(&p), 1);
5184 /// ```
5185 #[inline]
5186 pub fn legendre(&self, p: &Self) -> i32 {
5187 xmpz::legendre(self, p).cast()
5188 }
5189
5190 /// Calculates the Jacobi symbol (`self`/<i>n</i>) with the Kronecker
5191 /// extension.
5192 ///
5193 /// # Examples
5194 ///
5195 /// ```rust
5196 /// use rug::{Assign, Integer};
5197 /// let k = Integer::from(3);
5198 /// let mut n = Integer::from(16);
5199 /// assert_eq!(k.kronecker(&n), 1);
5200 /// n.assign(17);
5201 /// assert_eq!(k.kronecker(&n), -1);
5202 /// n.assign(18);
5203 /// assert_eq!(k.kronecker(&n), 0);
5204 /// ```
5205 #[inline]
5206 pub fn kronecker(&self, n: &Self) -> i32 {
5207 xmpz::kronecker(self, n).cast()
5208 }
5209
5210 /// Removes all occurrences of `factor`, and returns the number of
5211 /// occurrences removed.
5212 ///
5213 /// # Examples
5214 ///
5215 /// ```rust
5216 /// use rug::Integer;
5217 /// let mut i = Integer::from(Integer::u_pow_u(13, 50));
5218 /// i *= 1000;
5219 /// let (remove, count) = i.remove_factor(&Integer::from(13));
5220 /// assert_eq!(remove, 1000);
5221 /// assert_eq!(count, 50);
5222 /// ```
5223 #[inline]
5224 pub fn remove_factor(mut self, factor: &Self) -> (Self, u32) {
5225 let count = self.remove_factor_mut(factor);
5226 (self, count)
5227 }
5228
5229 /// Removes all occurrences of `factor`, and returns the number of
5230 /// occurrences removed.
5231 ///
5232 /// # Examples
5233 ///
5234 /// ```rust
5235 /// use rug::Integer;
5236 /// let mut i = Integer::from(Integer::u_pow_u(13, 50));
5237 /// i *= 1000;
5238 /// let count = i.remove_factor_mut(&Integer::from(13));
5239 /// assert_eq!(i, 1000);
5240 /// assert_eq!(count, 50);
5241 /// ```
5242 #[inline]
5243 pub fn remove_factor_mut(&mut self, factor: &Self) -> u32 {
5244 xmpz::remove(self, (), factor).unwrapped_cast()
5245 }
5246
5247 /// Removes all occurrences of `factor`, and counts the number of
5248 /// occurrences removed.
5249 ///
5250 /// The following are implemented with the returned [incomplete-computation
5251 /// value][icv] as `Src`:
5252 /// * <code>[Assign]\<Src> for [(][tuple][Integer][], [u32][][)][tuple]</code>
5253 /// * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [u32][][)][tuple]</code>
5254 /// * <code>[From]\<Src> for [(][tuple][Integer][], [u32][][)][tuple]</code>
5255 /// * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [u32][][)][tuple]> for Src</code>
5256 ///
5257 /// # Examples
5258 ///
5259 /// ```rust
5260 /// use rug::{Assign, Integer};
5261 /// let mut i = Integer::from(Integer::u_pow_u(13, 50));
5262 /// i *= 1000;
5263 /// let factor = Integer::from(13);
5264 /// let r = i.remove_factor_ref(&factor);
5265 /// let (mut j, mut count) = (Integer::new(), 0);
5266 /// (&mut j, &mut count).assign(r);
5267 /// assert_eq!(count, 50);
5268 /// assert_eq!(j, 1000);
5269 /// ```
5270 ///
5271 /// [icv]: crate#incomplete-computation-values
5272 #[inline]
5273 pub fn remove_factor_ref<'a>(&'a self, factor: &'a Self) -> RemoveFactorIncomplete<'a> {
5274 RemoveFactorIncomplete {
5275 ref_self: self,
5276 factor,
5277 }
5278 }
5279
5280 /// Computes the factorial of <i>n</i>.
5281 ///
5282 /// The following are implemented with the returned [incomplete-computation
5283 /// value][icv] as `Src`:
5284 /// * <code>[Assign]\<Src> for [Integer]</code>
5285 /// * <code>[From]\<Src> for [Integer]</code>
5286 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5287 ///
5288 /// # Examples
5289 ///
5290 /// ```rust
5291 /// use rug::{Complete, Integer};
5292 /// // 10 × 9 × 8 × 7 × 6 × 5 × 4 × 3 × 2 × 1
5293 /// assert_eq!(Integer::factorial(10).complete(), 3628800);
5294 /// ```
5295 ///
5296 /// [icv]: crate#incomplete-computation-values
5297 #[inline]
5298 pub fn factorial(n: u32) -> FactorialIncomplete {
5299 let n = n.into();
5300 FactorialIncomplete { n }
5301 }
5302
5303 /// Computes the double factorial of <i>n</i>.
5304 ///
5305 /// The following are implemented with the returned [incomplete-computation
5306 /// value][icv] as `Src`:
5307 /// * <code>[Assign]\<Src> for [Integer]</code>
5308 /// * <code>[From]\<Src> for [Integer]</code>
5309 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5310 ///
5311 /// # Examples
5312 ///
5313 /// ```rust
5314 /// use rug::{Complete, Integer};
5315 /// // 10 × 8 × 6 × 4 × 2
5316 /// assert_eq!(Integer::factorial_2(10).complete(), 3840);
5317 /// ```
5318 ///
5319 /// [icv]: crate#incomplete-computation-values
5320 #[inline]
5321 pub fn factorial_2(n: u32) -> Factorial2Incomplete {
5322 let n = n.into();
5323 Factorial2Incomplete { n }
5324 }
5325
5326 /// Computes the <i>m</i>-multi factorial of <i>n</i>.
5327 ///
5328 /// The following are implemented with the returned [incomplete-computation
5329 /// value][icv] as `Src`:
5330 /// * <code>[Assign]\<Src> for [Integer]</code>
5331 /// * <code>[From]\<Src> for [Integer]</code>
5332 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5333 ///
5334 /// # Examples
5335 ///
5336 /// ```rust
5337 /// use rug::{Complete, Integer};
5338 /// // 10 × 7 × 4 × 1
5339 /// assert_eq!(Integer::factorial_m(10, 3).complete(), 280);
5340 /// ```
5341 ///
5342 /// [icv]: crate#incomplete-computation-values
5343 #[inline]
5344 pub fn factorial_m(n: u32, m: u32) -> FactorialMIncomplete {
5345 let n = n.into();
5346 let m = m.into();
5347 FactorialMIncomplete { n, m }
5348 }
5349
5350 /// Computes the primorial of <i>n</i>.
5351 ///
5352 /// The following are implemented with the returned [incomplete-computation
5353 /// value][icv] as `Src`:
5354 /// * <code>[Assign]\<Src> for [Integer]</code>
5355 /// * <code>[From]\<Src> for [Integer]</code>
5356 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5357 ///
5358 /// # Examples
5359 ///
5360 /// ```rust
5361 /// use rug::{Complete, Integer};
5362 /// // 7 × 5 × 3 × 2
5363 /// assert_eq!(Integer::primorial(10).complete(), 210);
5364 /// ```
5365 ///
5366 /// [icv]: crate#incomplete-computation-values
5367 #[inline]
5368 pub fn primorial(n: u32) -> PrimorialIncomplete {
5369 let n = n.into();
5370 PrimorialIncomplete { n }
5371 }
5372
5373 /// Computes the binomial coefficient over <i>k</i>.
5374 ///
5375 /// # Examples
5376 ///
5377 /// ```rust
5378 /// use rug::Integer;
5379 /// // 7 choose 2 is 21
5380 /// let i = Integer::from(7);
5381 /// let bin = i.binomial(2);
5382 /// assert_eq!(bin, 21);
5383 /// ```
5384 #[inline]
5385 #[must_use]
5386 pub fn binomial(mut self, k: u32) -> Self {
5387 self.binomial_mut(k);
5388 self
5389 }
5390
5391 /// Computes the binomial coefficient over <i>k</i>.
5392 ///
5393 /// # Examples
5394 ///
5395 /// ```rust
5396 /// use rug::Integer;
5397 /// // 7 choose 2 is 21
5398 /// let mut i = Integer::from(7);
5399 /// i.binomial_mut(2);
5400 /// assert_eq!(i, 21);
5401 /// ```
5402 #[inline]
5403 pub fn binomial_mut(&mut self, k: u32) {
5404 xmpz::bin_ui(self, (), k.into());
5405 }
5406
5407 /// Computes the binomial coefficient over <i>k</i>.
5408 ///
5409 /// The following are implemented with the returned [incomplete-computation
5410 /// value][icv] as `Src`:
5411 /// * <code>[Assign]\<Src> for [Integer]</code>
5412 /// * <code>[From]\<Src> for [Integer]</code>
5413 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5414 ///
5415 /// # Examples
5416 ///
5417 /// ```rust
5418 /// use rug::{Complete, Integer};
5419 /// // 7 choose 2 is 21
5420 /// let i = Integer::from(7);
5421 /// assert_eq!(i.binomial_ref(2).complete(), 21);
5422 /// ```
5423 ///
5424 /// [icv]: crate#incomplete-computation-values
5425 #[inline]
5426 pub fn binomial_ref(&self, k: u32) -> BinomialIncomplete<'_> {
5427 let k = k.into();
5428 BinomialIncomplete { ref_self: self, k }
5429 }
5430
5431 /// Computes the binomial coefficient <i>n</i> over <i>k</i>.
5432 ///
5433 /// The following are implemented with the returned [incomplete-computation
5434 /// value][icv] as `Src`:
5435 /// * <code>[Assign]\<Src> for [Integer]</code>
5436 /// * <code>[From]\<Src> for [Integer]</code>
5437 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5438 ///
5439 /// # Examples
5440 ///
5441 /// ```rust
5442 /// use rug::Integer;
5443 /// // 7 choose 2 is 21
5444 /// let b = Integer::binomial_u(7, 2);
5445 /// let i = Integer::from(b);
5446 /// assert_eq!(i, 21);
5447 /// ```
5448 ///
5449 /// [icv]: crate#incomplete-computation-values
5450 #[inline]
5451 pub fn binomial_u(n: u32, k: u32) -> BinomialUIncomplete {
5452 let n = n.into();
5453 let k = k.into();
5454 BinomialUIncomplete { n, k }
5455 }
5456
5457 /// Computes the Fibonacci number.
5458 ///
5459 /// The following are implemented with the returned [incomplete-computation
5460 /// value][icv] as `Src`:
5461 /// * <code>[Assign]\<Src> for [Integer]</code>
5462 /// * <code>[From]\<Src> for [Integer]</code>
5463 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5464 ///
5465 /// This function is meant for an isolated number. If a sequence of
5466 /// Fibonacci numbers is required, the first two values of the sequence
5467 /// should be computed with the [`fibonacci_2`][Integer::fibonacci_2]
5468 /// method, then iterations should be used.
5469 ///
5470 /// # Examples
5471 ///
5472 /// ```rust
5473 /// use rug::{Complete, Integer};
5474 /// assert_eq!(Integer::fibonacci(12).complete(), 144);
5475 /// ```
5476 ///
5477 /// [icv]: crate#incomplete-computation-values
5478 #[inline]
5479 pub fn fibonacci(n: u32) -> FibonacciIncomplete {
5480 let n = n.into();
5481 FibonacciIncomplete { n }
5482 }
5483
5484 /// Computes a Fibonacci number, and the previous Fibonacci number.
5485 ///
5486 /// The following are implemented with the returned [incomplete-computation
5487 /// value][icv] as `Src`:
5488 /// * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
5489 /// * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
5490 /// * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
5491 /// * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
5492 ///
5493 /// This function is meant to calculate isolated numbers. If a sequence of
5494 /// Fibonacci numbers is required, the first two values of the sequence
5495 /// should be computed with this function, then iterations should be used.
5496 ///
5497 /// # Examples
5498 ///
5499 /// ```rust
5500 /// use rug::{Assign, Integer};
5501 /// let f = Integer::fibonacci_2(12);
5502 /// let mut pair = <(Integer, Integer)>::from(f);
5503 /// assert_eq!(pair.0, 144);
5504 /// assert_eq!(pair.1, 89);
5505 /// // Fibonacci number F[-1] is 1
5506 /// pair.assign(Integer::fibonacci_2(0));
5507 /// assert_eq!(pair.0, 0);
5508 /// assert_eq!(pair.1, 1);
5509 /// ```
5510 ///
5511 /// [icv]: crate#incomplete-computation-values
5512 #[inline]
5513 pub fn fibonacci_2(n: u32) -> Fibonacci2Incomplete {
5514 let n = n.into();
5515 Fibonacci2Incomplete { n }
5516 }
5517
5518 /// Computes the Lucas number.
5519 ///
5520 /// The following are implemented with the returned [incomplete-computation
5521 /// value][icv] as `Src`:
5522 /// * <code>[Assign]\<Src> for [Integer]</code>
5523 /// * <code>[From]\<Src> for [Integer]</code>
5524 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5525 ///
5526 /// This function is meant for an isolated number. If a sequence of Lucas
5527 /// numbers is required, the first two values of the sequence should be
5528 /// computed with the [`lucas_2`][Integer::lucas_2] method, then iterations
5529 /// should be used.
5530 ///
5531 /// # Examples
5532 ///
5533 /// ```rust
5534 /// use rug::{Complete, Integer};
5535 /// assert_eq!(Integer::lucas(12).complete(), 322);
5536 /// ```
5537 ///
5538 /// [icv]: crate#incomplete-computation-values
5539 #[inline]
5540 pub fn lucas(n: u32) -> LucasIncomplete {
5541 let n = n.into();
5542 LucasIncomplete { n }
5543 }
5544
5545 /// Computes a Lucas number, and the previous Lucas number.
5546 ///
5547 /// The following are implemented with the returned [incomplete-computation
5548 /// value][icv] as `Src`:
5549 /// * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
5550 /// * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
5551 /// * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
5552 /// * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
5553 ///
5554 /// This function is meant to calculate isolated numbers. If a sequence of
5555 /// Lucas numbers is required, the first two values of the sequence should
5556 /// be computed with this function, then iterations should be used.
5557 ///
5558 /// # Examples
5559 ///
5560 /// ```rust
5561 /// use rug::{Assign, Integer};
5562 /// let l = Integer::lucas_2(12);
5563 /// let mut pair = <(Integer, Integer)>::from(l);
5564 /// assert_eq!(pair.0, 322);
5565 /// assert_eq!(pair.1, 199);
5566 /// pair.assign(Integer::lucas_2(0));
5567 /// assert_eq!(pair.0, 2);
5568 /// assert_eq!(pair.1, -1);
5569 /// ```
5570 ///
5571 /// [icv]: crate#incomplete-computation-values
5572 #[inline]
5573 pub fn lucas_2(n: u32) -> Lucas2Incomplete {
5574 let n = n.into();
5575 Lucas2Incomplete { n }
5576 }
5577
5578 #[cfg(feature = "rand")]
5579 /// Generates a random number with a specified maximum number of bits.
5580 ///
5581 /// The following are implemented with the returned [incomplete-computation
5582 /// value][icv] as `Src`:
5583 /// * <code>[Assign]\<Src> for [Integer]</code>
5584 /// * <code>[From]\<Src> for [Integer]</code>
5585 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5586 ///
5587 /// # Examples
5588 ///
5589 /// ```rust
5590 /// use rug::rand::RandState;
5591 /// use rug::{Assign, Integer};
5592 /// let mut rand = RandState::new();
5593 /// let mut i = Integer::from(Integer::random_bits(0, &mut rand));
5594 /// assert_eq!(i, 0);
5595 /// i.assign(Integer::random_bits(80, &mut rand));
5596 /// assert!(i.significant_bits() <= 80);
5597 /// ```
5598 ///
5599 /// [icv]: crate#incomplete-computation-values
5600 #[inline]
5601 pub fn random_bits(bits: u32, rng: &mut dyn MutRandState) -> RandomBitsIncomplete {
5602 let bits = bits.into();
5603 RandomBitsIncomplete { bits, rng }
5604 }
5605
5606 #[cfg(feature = "rand")]
5607 /// Generates a non-negative random number below the given boundary value.
5608 ///
5609 /// # Panics
5610 ///
5611 /// Panics if the boundary value is less than or equal to zero.
5612 ///
5613 /// # Examples
5614 ///
5615 /// ```rust
5616 /// use rug::rand::RandState;
5617 /// use rug::Integer;
5618 /// let mut rand = RandState::new();
5619 /// let i = Integer::from(15);
5620 /// let below = i.random_below(&mut rand);
5621 /// println!("0 ≤ {} < 15", below);
5622 /// assert!(below < 15);
5623 /// ```
5624 #[inline]
5625 #[must_use]
5626 pub fn random_below(mut self, rng: &mut dyn MutRandState) -> Self {
5627 self.random_below_mut(rng);
5628 self
5629 }
5630
5631 #[cfg(feature = "rand")]
5632 /// Generates a non-negative random number below the given boundary value.
5633 ///
5634 /// # Panics
5635 ///
5636 /// Panics if the boundary value is less than or equal to zero.
5637 ///
5638 /// # Examples
5639 ///
5640 /// ```rust
5641 /// use rug::rand::RandState;
5642 /// use rug::Integer;
5643 /// let mut rand = RandState::new();
5644 /// let mut i = Integer::from(15);
5645 /// i.random_below_mut(&mut rand);
5646 /// println!("0 ≤ {} < 15", i);
5647 /// assert!(i < 15);
5648 /// ```
5649 #[inline]
5650 pub fn random_below_mut(&mut self, rng: &mut dyn MutRandState) {
5651 xmpz::urandomm(self, rng, ());
5652 }
5653
5654 #[cfg(feature = "rand")]
5655 /// Generates a non-negative random number below the given boundary value.
5656 ///
5657 /// The following are implemented with the returned [incomplete-computation
5658 /// value][icv] as `Src`:
5659 /// * <code>[Assign]\<Src> for [Integer]</code>
5660 /// * <code>[From]\<Src> for [Integer]</code>
5661 /// * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5662 ///
5663 /// # Panics
5664 ///
5665 /// Panics if the boundary value is less than or equal to zero.
5666 ///
5667 /// # Examples
5668 ///
5669 /// ```rust
5670 /// use rug::rand::RandState;
5671 /// use rug::Integer;
5672 /// let mut rand = RandState::new();
5673 /// let bound = Integer::from(15);
5674 /// let i = Integer::from(bound.random_below_ref(&mut rand));
5675 /// println!("0 ≤ {} < {}", i, bound);
5676 /// assert!(i < bound);
5677 /// ```
5678 ///
5679 /// [icv]: crate#incomplete-computation-values
5680 #[inline]
5681 pub fn random_below_ref<'a>(
5682 &'a self,
5683 rng: &'a mut dyn MutRandState,
5684 ) -> RandomBelowIncomplete<'a> {
5685 RandomBelowIncomplete {
5686 ref_self: self,
5687 rng,
5688 }
5689 }
5690
5691 /// This method has been renamed to [`extended_gcd`][Integer::extended_gcd].
5692 #[deprecated(since = "1.18.0", note = "renamed to `extended_gcd`")]
5693 #[inline]
5694 pub fn gcd_cofactors(self, other: Self, rop: Self) -> (Self, Self, Self) {
5695 self.extended_gcd(other, rop)
5696 }
5697
5698 /// This method has been renamed to
5699 /// [`extended_gcd_mut`][Integer::extended_gcd_mut].
5700 #[deprecated(since = "1.18.0", note = "renamed to `extended_gcd_mut`")]
5701 #[inline]
5702 pub fn gcd_cofactors_mut(&mut self, other: &mut Self, rop: &mut Self) {
5703 self.extended_gcd_mut(other, rop);
5704 }
5705
5706 /// This method has been renamed to
5707 /// [`extended_gcd_ref`][Integer::extended_gcd_ref].
5708 #[deprecated(since = "1.18.0", note = "renamed to `extended_gcd_ref`")]
5709 #[inline]
5710 pub fn gcd_cofactors_ref<'a>(&'a self, other: &'a Self) -> GcdExtIncomplete<'a> {
5711 self.extended_gcd_ref(other)
5712 }
5713}
5714
5715#[derive(Debug)]
5716pub struct SumIncomplete<'a, I>
5717where
5718 I: Iterator<Item = &'a Integer>,
5719{
5720 values: I,
5721}
5722
5723impl<'a, I> Assign<SumIncomplete<'a, I>> for Integer
5724where
5725 I: Iterator<Item = &'a Self>,
5726{
5727 fn assign(&mut self, mut src: SumIncomplete<'a, I>) {
5728 if let Some(first) = src.values.next() {
5729 self.assign(first);
5730 } else {
5731 self.assign(0u32);
5732 return;
5733 }
5734 self.add_assign(src);
5735 }
5736}
5737
5738impl<'a, I> From<SumIncomplete<'a, I>> for Integer
5739where
5740 I: Iterator<Item = &'a Self>,
5741{
5742 fn from(mut src: SumIncomplete<'a, I>) -> Self {
5743 let mut dst = match src.values.next() {
5744 Some(first) => first.clone(),
5745 None => return Integer::new(),
5746 };
5747 dst.add_assign(src);
5748 dst
5749 }
5750}
5751
5752impl<'a, I> Complete for SumIncomplete<'a, I>
5753where
5754 I: Iterator<Item = &'a Integer>,
5755{
5756 type Completed = Integer;
5757 #[inline]
5758 fn complete(self) -> Integer {
5759 Integer::from(self)
5760 }
5761}
5762
5763impl<'a, I> Add<SumIncomplete<'a, I>> for Integer
5764where
5765 I: Iterator<Item = &'a Self>,
5766{
5767 type Output = Self;
5768 #[inline]
5769 fn add(mut self, rhs: SumIncomplete<'a, I>) -> Self {
5770 self.add_assign(rhs);
5771 self
5772 }
5773}
5774
5775impl<'a, I> Add<Integer> for SumIncomplete<'a, I>
5776where
5777 I: Iterator<Item = &'a Integer>,
5778{
5779 type Output = Integer;
5780 #[inline]
5781 fn add(self, mut rhs: Integer) -> Integer {
5782 rhs.add_assign(self);
5783 rhs
5784 }
5785}
5786
5787impl<'a, I> AddAssign<SumIncomplete<'a, I>> for Integer
5788where
5789 I: Iterator<Item = &'a Self>,
5790{
5791 fn add_assign(&mut self, src: SumIncomplete<'a, I>) {
5792 for i in src.values {
5793 self.add_assign(i);
5794 }
5795 }
5796}
5797
5798impl<'a, I> Sub<SumIncomplete<'a, I>> for Integer
5799where
5800 I: Iterator<Item = &'a Self>,
5801{
5802 type Output = Self;
5803 #[inline]
5804 fn sub(mut self, rhs: SumIncomplete<'a, I>) -> Self {
5805 self.sub_assign(rhs);
5806 self
5807 }
5808}
5809
5810impl<'a, I> Sub<Integer> for SumIncomplete<'a, I>
5811where
5812 I: Iterator<Item = &'a Integer>,
5813{
5814 type Output = Integer;
5815 #[inline]
5816 fn sub(self, mut rhs: Integer) -> Integer {
5817 rhs.neg_assign();
5818 rhs.add_assign(self);
5819 rhs
5820 }
5821}
5822
5823impl<'a, I> SubAssign<SumIncomplete<'a, I>> for Integer
5824where
5825 I: Iterator<Item = &'a Self>,
5826{
5827 fn sub_assign(&mut self, src: SumIncomplete<'a, I>) {
5828 for i in src.values {
5829 self.sub_assign(i);
5830 }
5831 }
5832}
5833
5834impl<'a, I> SubFrom<SumIncomplete<'a, I>> for Integer
5835where
5836 I: Iterator<Item = &'a Self>,
5837{
5838 fn sub_from(&mut self, src: SumIncomplete<'a, I>) {
5839 self.neg_assign();
5840 self.add_assign(src);
5841 }
5842}
5843
5844#[derive(Debug)]
5845pub struct DotIncomplete<'a, I>
5846where
5847 I: Iterator<Item = (&'a Integer, &'a Integer)>,
5848{
5849 values: I,
5850}
5851
5852impl<'a, I> Assign<DotIncomplete<'a, I>> for Integer
5853where
5854 I: Iterator<Item = (&'a Integer, &'a Integer)>,
5855{
5856 fn assign(&mut self, mut src: DotIncomplete<'a, I>) {
5857 if let Some(first) = src.values.next() {
5858 self.assign(first.0 * first.1);
5859 } else {
5860 self.assign(0u32);
5861 return;
5862 }
5863 self.add_assign(src);
5864 }
5865}
5866
5867impl<'a, I> From<DotIncomplete<'a, I>> for Integer
5868where
5869 I: Iterator<Item = (&'a Integer, &'a Integer)>,
5870{
5871 fn from(mut src: DotIncomplete<'a, I>) -> Self {
5872 let mut dst = match src.values.next() {
5873 Some(first) => Integer::from(first.0 * first.1),
5874 None => return Integer::new(),
5875 };
5876 dst.add_assign(src);
5877 dst
5878 }
5879}
5880
5881impl<'a, I> Complete for DotIncomplete<'a, I>
5882where
5883 I: Iterator<Item = (&'a Integer, &'a Integer)>,
5884{
5885 type Completed = Integer;
5886 #[inline]
5887 fn complete(self) -> Integer {
5888 Integer::from(self)
5889 }
5890}
5891
5892impl<'a, I> Add<DotIncomplete<'a, I>> for Integer
5893where
5894 I: Iterator<Item = (&'a Integer, &'a Integer)>,
5895{
5896 type Output = Self;
5897 #[inline]
5898 fn add(mut self, rhs: DotIncomplete<'a, I>) -> Self {
5899 self.add_assign(rhs);
5900 self
5901 }
5902}
5903
5904impl<'a, I> Add<Integer> for DotIncomplete<'a, I>
5905where
5906 I: Iterator<Item = (&'a Integer, &'a Integer)>,
5907{
5908 type Output = Integer;
5909 #[inline]
5910 fn add(self, mut rhs: Integer) -> Integer {
5911 rhs.add_assign(self);
5912 rhs
5913 }
5914}
5915
5916impl<'a, I> AddAssign<DotIncomplete<'a, I>> for Integer
5917where
5918 I: Iterator<Item = (&'a Integer, &'a Integer)>,
5919{
5920 fn add_assign(&mut self, src: DotIncomplete<'a, I>) {
5921 for i in src.values {
5922 #[allow(clippy::suspicious_op_assign_impl)]
5923 AddAssign::add_assign(self, i.0 * i.1);
5924 }
5925 }
5926}
5927
5928impl<'a, I> Sub<DotIncomplete<'a, I>> for Integer
5929where
5930 I: Iterator<Item = (&'a Integer, &'a Integer)>,
5931{
5932 type Output = Self;
5933 #[inline]
5934 fn sub(mut self, rhs: DotIncomplete<'a, I>) -> Self {
5935 self.sub_assign(rhs);
5936 self
5937 }
5938}
5939
5940impl<'a, I> Sub<Integer> for DotIncomplete<'a, I>
5941where
5942 I: Iterator<Item = (&'a Integer, &'a Integer)>,
5943{
5944 type Output = Integer;
5945 #[inline]
5946 fn sub(self, mut rhs: Integer) -> Integer {
5947 rhs.neg_assign();
5948 rhs.add_assign(self);
5949 rhs
5950 }
5951}
5952
5953impl<'a, I> SubAssign<DotIncomplete<'a, I>> for Integer
5954where
5955 I: Iterator<Item = (&'a Integer, &'a Integer)>,
5956{
5957 fn sub_assign(&mut self, src: DotIncomplete<'a, I>) {
5958 for i in src.values {
5959 #[allow(clippy::suspicious_op_assign_impl)]
5960 SubAssign::sub_assign(self, i.0 * i.1);
5961 }
5962 }
5963}
5964
5965impl<'a, I> SubFrom<DotIncomplete<'a, I>> for Integer
5966where
5967 I: Iterator<Item = (&'a Integer, &'a Integer)>,
5968{
5969 fn sub_from(&mut self, src: DotIncomplete<'a, I>) {
5970 self.neg_assign();
5971 self.add_assign(src);
5972 }
5973}
5974
5975#[derive(Debug)]
5976pub struct ProductIncomplete<'a, I>
5977where
5978 I: Iterator<Item = &'a Integer>,
5979{
5980 values: I,
5981}
5982
5983impl<'a, I> Assign<ProductIncomplete<'a, I>> for Integer
5984where
5985 I: Iterator<Item = &'a Self>,
5986{
5987 fn assign(&mut self, mut src: ProductIncomplete<'a, I>) {
5988 if let Some(first) = src.values.next() {
5989 self.assign(first);
5990 } else {
5991 self.assign(1u32);
5992 return;
5993 }
5994 self.mul_assign(src);
5995 }
5996}
5997
5998impl<'a, I> From<ProductIncomplete<'a, I>> for Integer
5999where
6000 I: Iterator<Item = &'a Self>,
6001{
6002 fn from(mut src: ProductIncomplete<'a, I>) -> Self {
6003 let mut dst = match src.values.next() {
6004 Some(first) => first.clone(),
6005 None => return Integer::from(1),
6006 };
6007 dst.mul_assign(src);
6008 dst
6009 }
6010}
6011
6012impl<'a, I> Complete for ProductIncomplete<'a, I>
6013where
6014 I: Iterator<Item = &'a Integer>,
6015{
6016 type Completed = Integer;
6017 #[inline]
6018 fn complete(self) -> Integer {
6019 Integer::from(self)
6020 }
6021}
6022
6023impl<'a, I> Mul<ProductIncomplete<'a, I>> for Integer
6024where
6025 I: Iterator<Item = &'a Self>,
6026{
6027 type Output = Self;
6028 #[inline]
6029 fn mul(mut self, rhs: ProductIncomplete<'a, I>) -> Self {
6030 self.mul_assign(rhs);
6031 self
6032 }
6033}
6034
6035impl<'a, I> Mul<Integer> for ProductIncomplete<'a, I>
6036where
6037 I: Iterator<Item = &'a Integer>,
6038{
6039 type Output = Integer;
6040 #[inline]
6041 fn mul(self, mut rhs: Integer) -> Integer {
6042 rhs.mul_assign(self);
6043 rhs
6044 }
6045}
6046
6047impl<'a, I> MulAssign<ProductIncomplete<'a, I>> for Integer
6048where
6049 I: Iterator<Item = &'a Self>,
6050{
6051 fn mul_assign(&mut self, mut src: ProductIncomplete<'a, I>) {
6052 let mut other = match src.values.next() {
6053 Some(next) => Integer::from(&*self * next),
6054 None => return,
6055 };
6056 loop {
6057 if let Some(next) = src.values.next() {
6058 self.assign(&other * next);
6059 } else {
6060 self.assign(other);
6061 return;
6062 }
6063 match src.values.next() {
6064 Some(next) => {
6065 other.assign(&*self * next);
6066 }
6067 None => {
6068 return;
6069 }
6070 }
6071 if self.is_zero() {
6072 return;
6073 }
6074 }
6075 }
6076}
6077
6078ref_math_op1! { Integer; xmpz::abs; struct AbsIncomplete {} }
6079ref_math_op1! { Integer; xmpz::signum; struct SignumIncomplete {} }
6080
6081#[derive(Debug)]
6082pub struct ClampIncomplete<'s, 'min, 'max, Min, Max>
6083where
6084 Integer: PartialOrd<Min> + PartialOrd<Max> + for<'a> Assign<&'a Min> + for<'a> Assign<&'a Max>,
6085{
6086 ref_self: &'s Integer,
6087 min: &'min Min,
6088 max: &'max Max,
6089}
6090
6091impl<Min, Max> Assign<ClampIncomplete<'_, '_, '_, Min, Max>> for Integer
6092where
6093 Self: PartialOrd<Min> + PartialOrd<Max> + for<'a> Assign<&'a Min> + for<'a> Assign<&'a Max>,
6094{
6095 #[inline]
6096 fn assign(&mut self, src: ClampIncomplete<Min, Max>) {
6097 if src.ref_self.lt(src.min) {
6098 self.assign(src.min);
6099 assert!(!(*self).gt(src.max), "minimum larger than maximum");
6100 } else if src.ref_self.gt(src.max) {
6101 self.assign(src.max);
6102 assert!(!(*self).lt(src.min), "minimum larger than maximum");
6103 } else {
6104 self.assign(src.ref_self);
6105 }
6106 }
6107}
6108
6109impl<Min, Max> From<ClampIncomplete<'_, '_, '_, Min, Max>> for Integer
6110where
6111 Self: PartialOrd<Min> + PartialOrd<Max> + for<'a> Assign<&'a Min> + for<'a> Assign<&'a Max>,
6112{
6113 #[inline]
6114 fn from(src: ClampIncomplete<Min, Max>) -> Self {
6115 let mut dst = Integer::new();
6116 dst.assign(src);
6117 dst
6118 }
6119}
6120
6121impl<Min, Max> Complete for ClampIncomplete<'_, '_, '_, Min, Max>
6122where
6123 Integer: PartialOrd<Min> + PartialOrd<Max> + for<'a> Assign<&'a Min> + for<'a> Assign<&'a Max>,
6124{
6125 type Completed = Integer;
6126 #[inline]
6127 fn complete(self) -> Integer {
6128 Integer::from(self)
6129 }
6130}
6131
6132ref_math_op1! { Integer; xmpz::fdiv_r_2exp; struct KeepBitsIncomplete { n: bitcnt_t } }
6133ref_math_op1! { Integer; xmpz::keep_signed_bits; struct KeepSignedBitsIncomplete { n: bitcnt_t } }
6134ref_math_op1! { Integer; xmpz::next_pow_of_two; struct NextPowerOfTwoIncomplete {} }
6135ref_math_op2! { Integer; xmpz::modulo; struct ModuloIncomplete { divisor } }
6136ref_math_op2_2! { Integer; xmpz::tdiv_qr; struct DivRemIncomplete { divisor } }
6137ref_math_op2_2! { Integer; xmpz::cdiv_qr; struct DivRemCeilIncomplete { divisor } }
6138ref_math_op2_2! { Integer; xmpz::fdiv_qr; struct DivRemFloorIncomplete { divisor } }
6139ref_math_op2_2! { Integer; xmpz::rdiv_qr; struct DivRemRoundIncomplete { divisor } }
6140ref_math_op2_2! { Integer; xmpz::ediv_qr; struct DivRemEucIncomplete { divisor } }
6141ref_math_op2! { Integer; xmpz::divexact; struct DivExactIncomplete { divisor } }
6142ref_math_op1! { Integer; xmpz::divexact_u32; struct DivExactUIncomplete { divisor: u32 } }
6143
6144#[derive(Debug)]
6145pub struct PowModIncomplete<'a> {
6146 ref_self: Option<&'a Integer>,
6147 sinverse: Option<Integer>,
6148 exponent: &'a Integer,
6149 modulo: &'a Integer,
6150}
6151
6152impl Assign<PowModIncomplete<'_>> for Integer {
6153 #[inline]
6154 fn assign(&mut self, src: PowModIncomplete<'_>) {
6155 match (src.ref_self, src.sinverse) {
6156 (Some(base), None) => {
6157 debug_assert!(!src.exponent.is_negative());
6158 xmpz::pow_mod(self, base, src.exponent, src.modulo);
6159 }
6160 (None, Some(sinverse)) => {
6161 debug_assert!(src.exponent.is_negative());
6162 xmpz::pow_mod(self, &sinverse, src.exponent, src.modulo);
6163 }
6164 _ => unreachable!(),
6165 }
6166 }
6167}
6168
6169// do not use from_assign! macro to reuse sinverse
6170impl From<PowModIncomplete<'_>> for Integer {
6171 #[inline]
6172 fn from(src: PowModIncomplete<'_>) -> Self {
6173 match (src.ref_self, src.sinverse) {
6174 (Some(base), None) => {
6175 debug_assert!(!src.exponent.is_negative());
6176 let mut dst = Integer::new();
6177 xmpz::pow_mod(&mut dst, base, src.exponent, src.modulo);
6178 dst
6179 }
6180 (None, Some(mut sinverse)) => {
6181 debug_assert!(src.exponent.is_negative());
6182 xmpz::pow_mod(&mut sinverse, (), src.exponent, src.modulo);
6183 sinverse
6184 }
6185 _ => unreachable!(),
6186 }
6187 }
6188}
6189
6190impl Complete for PowModIncomplete<'_> {
6191 type Completed = Integer;
6192 #[inline]
6193 fn complete(self) -> Integer {
6194 Integer::from(self)
6195 }
6196}
6197
6198pub struct SecurePowModIncomplete<'a> {
6199 ref_self: &'a Integer,
6200 exponent: &'a Integer,
6201 modulo: &'a Integer,
6202}
6203
6204impl Assign<SecurePowModIncomplete<'_>> for Integer {
6205 #[inline]
6206 fn assign(&mut self, src: SecurePowModIncomplete<'_>) {
6207 xmpz::powm_sec(self, src.ref_self, src.exponent, src.modulo);
6208 }
6209}
6210
6211from_assign! { SecurePowModIncomplete<'_> => Integer }
6212
6213ref_math_op0! { Integer; xmpz::u32_pow_u32; struct UPowUIncomplete { base: u32, exponent: u32 } }
6214ref_math_op0! { Integer; xmpz::i32_pow_u32; struct IPowUIncomplete { base: i32, exponent: u32 } }
6215ref_math_op1! { Integer; xmpz::root; struct RootIncomplete { n: c_ulong } }
6216ref_math_op1_2! { Integer; xmpz::rootrem; struct RootRemIncomplete { n: c_ulong } }
6217ref_math_op1! { Integer; xmpz::sqrt; struct SqrtIncomplete {} }
6218ref_math_op1_2! { Integer; xmpz::sqrtrem; struct SqrtRemIncomplete {} }
6219ref_math_op1! { Integer; xmpz::nextprime; struct NextPrimeIncomplete {} }
6220ref_math_op1! { Integer; xmpz::prevprime; struct PrevPrimeIncomplete {} }
6221ref_math_op2! { Integer; xmpz::gcd; struct GcdIncomplete { other } }
6222ref_math_op1! { Integer; xmpz::gcd_ui; struct GcdUIncomplete { other: c_ulong } }
6223
6224impl From<GcdUIncomplete<'_>> for Option<u32> {
6225 #[inline]
6226 fn from(src: GcdUIncomplete) -> Self {
6227 let gcd = xmpz::gcd_opt_ui(None, src.ref_self, src.other.into());
6228 if gcd == 0 && !src.ref_self.is_zero() {
6229 None
6230 } else {
6231 gcd.checked_cast()
6232 }
6233 }
6234}
6235
6236#[derive(Debug)]
6237pub struct GcdExtIncomplete<'a> {
6238 ref_self: &'a Integer,
6239 other: &'a Integer,
6240}
6241
6242impl Assign<GcdExtIncomplete<'_>> for (&mut Integer, &mut Integer, &mut Integer) {
6243 #[inline]
6244 fn assign(&mut self, src: GcdExtIncomplete<'_>) {
6245 xmpz::gcdext(self.0, self.1, Some(self.2), src.ref_self, src.other);
6246 }
6247}
6248
6249impl Assign<GcdExtIncomplete<'_>> for (Integer, Integer, Integer) {
6250 #[inline]
6251 fn assign(&mut self, src: GcdExtIncomplete<'_>) {
6252 (&mut self.0, &mut self.1, &mut self.2).assign(src);
6253 }
6254}
6255
6256from_assign! { GcdExtIncomplete<'_> => Integer, Integer, Integer }
6257
6258impl Assign<GcdExtIncomplete<'_>> for (&mut Integer, &mut Integer) {
6259 #[inline]
6260 fn assign(&mut self, src: GcdExtIncomplete<'_>) {
6261 xmpz::gcdext(self.0, self.1, None, src.ref_self, src.other);
6262 }
6263}
6264
6265impl Assign<GcdExtIncomplete<'_>> for (Integer, Integer) {
6266 #[inline]
6267 fn assign(&mut self, src: GcdExtIncomplete<'_>) {
6268 Assign::assign(&mut (&mut self.0, &mut self.1), src);
6269 }
6270}
6271
6272impl From<GcdExtIncomplete<'_>> for (Integer, Integer) {
6273 #[inline]
6274 fn from(src: GcdExtIncomplete<'_>) -> Self {
6275 let mut dst = Self::default();
6276 Assign::assign(&mut (&mut dst.0, &mut dst.1), src);
6277 dst
6278 }
6279}
6280
6281ref_math_op2! { Integer; xmpz::lcm; struct LcmIncomplete { other } }
6282ref_math_op1! { Integer; xmpz::lcm_ui; struct LcmUIncomplete { other: c_ulong } }
6283
6284#[derive(Debug)]
6285pub struct InvertIncomplete<'a> {
6286 sinverse: Integer,
6287 modulo: &'a Integer,
6288}
6289
6290impl Assign<InvertIncomplete<'_>> for Integer {
6291 #[inline]
6292 fn assign(&mut self, src: InvertIncomplete<'_>) {
6293 xmpz::finish_invert(self, &src.sinverse, src.modulo);
6294 }
6295}
6296
6297// do not use from_assign! macro to reuse sinverse
6298impl From<InvertIncomplete<'_>> for Integer {
6299 #[inline]
6300 fn from(mut src: InvertIncomplete<'_>) -> Self {
6301 xmpz::finish_invert(&mut src.sinverse, (), src.modulo);
6302 src.sinverse
6303 }
6304}
6305
6306impl Complete for InvertIncomplete<'_> {
6307 type Completed = Integer;
6308 #[inline]
6309 fn complete(self) -> Integer {
6310 Integer::from(self)
6311 }
6312}
6313
6314#[derive(Debug)]
6315pub struct RemoveFactorIncomplete<'a> {
6316 ref_self: &'a Integer,
6317 factor: &'a Integer,
6318}
6319
6320impl Assign<RemoveFactorIncomplete<'_>> for (&mut Integer, &mut u32) {
6321 #[inline]
6322 fn assign(&mut self, src: RemoveFactorIncomplete<'_>) {
6323 *self.1 = xmpz::remove(self.0, src.ref_self, src.factor).unwrapped_cast();
6324 }
6325}
6326
6327impl Assign<RemoveFactorIncomplete<'_>> for (Integer, u32) {
6328 #[inline]
6329 fn assign(&mut self, src: RemoveFactorIncomplete<'_>) {
6330 (&mut self.0, &mut self.1).assign(src);
6331 }
6332}
6333
6334from_assign! { RemoveFactorIncomplete<'_> => Integer, u32 }
6335
6336ref_math_op0! { Integer; xmpz::fac_ui; struct FactorialIncomplete { n: c_ulong } }
6337ref_math_op0! { Integer; xmpz::twofac_ui; struct Factorial2Incomplete { n: c_ulong } }
6338ref_math_op0! { Integer; xmpz::mfac_uiui; struct FactorialMIncomplete { n: c_ulong, m: c_ulong } }
6339ref_math_op0! { Integer; xmpz::primorial_ui; struct PrimorialIncomplete { n: c_ulong } }
6340ref_math_op1! { Integer; xmpz::bin_ui; struct BinomialIncomplete { k: c_ulong } }
6341ref_math_op0! { Integer; xmpz::bin_uiui; struct BinomialUIncomplete { n: c_ulong, k: c_ulong } }
6342ref_math_op0! { Integer; xmpz::fib_ui; struct FibonacciIncomplete { n: c_ulong } }
6343ref_math_op0_2! { Integer; xmpz::fib2_ui; struct Fibonacci2Incomplete { n: c_ulong } }
6344ref_math_op0! { Integer; xmpz::lucnum_ui; struct LucasIncomplete { n: c_ulong } }
6345ref_math_op0_2! { Integer; xmpz::lucnum2_ui; struct Lucas2Incomplete { n: c_ulong } }
6346
6347#[cfg(feature = "rand")]
6348pub struct RandomBitsIncomplete<'a> {
6349 bits: bitcnt_t,
6350 rng: &'a mut dyn MutRandState,
6351}
6352
6353#[cfg(feature = "rand")]
6354impl Assign<RandomBitsIncomplete<'_>> for Integer {
6355 #[inline]
6356 fn assign(&mut self, src: RandomBitsIncomplete) {
6357 xmpz::urandomb(self, src.rng, src.bits);
6358 }
6359}
6360
6361#[cfg(feature = "rand")]
6362from_assign! { RandomBitsIncomplete<'_> => Integer }
6363
6364#[cfg(feature = "rand")]
6365pub struct RandomBelowIncomplete<'a> {
6366 ref_self: &'a Integer,
6367 rng: &'a mut dyn MutRandState,
6368}
6369
6370#[cfg(feature = "rand")]
6371impl Assign<RandomBelowIncomplete<'_>> for Integer {
6372 #[inline]
6373 fn assign(&mut self, src: RandomBelowIncomplete) {
6374 xmpz::urandomm(self, src.rng, src.ref_self);
6375 }
6376}
6377
6378#[cfg(feature = "rand")]
6379from_assign! { RandomBelowIncomplete<'_> => Integer }
6380
6381pub(crate) fn req_chars(i: &Integer, radix: i32, extra: usize) -> usize {
6382 assert!((2..=36).contains(&radix), "radix out of range");
6383 let size = unsafe { gmp::mpz_sizeinbase(i.as_raw(), radix) };
6384 let size_extra = size.checked_add(extra).expect("overflow");
6385 if i.is_negative() {
6386 size_extra.checked_add(1).expect("overflow")
6387 } else {
6388 size_extra
6389 }
6390}
6391
6392pub(crate) fn append_to_string(s: &mut StringLike, i: &Integer, radix: i32, to_upper: bool) {
6393 // add 1 for nul
6394 let size = req_chars(i, radix, 1);
6395 s.reserve(size);
6396 let reserved_ptr = s.as_str().as_ptr();
6397 let case_radix = if to_upper { -radix } else { radix };
6398 unsafe {
6399 let alloced = s.reserved_space();
6400 gmp::mpz_get_str(
6401 misc::cast_ptr_mut(alloced.as_mut_ptr()),
6402 case_radix.cast(),
6403 i.as_raw(),
6404 );
6405 let nul_index = alloced
6406 .iter()
6407 .position(|&x: &MaybeUninit<u8>| {
6408 // SAFETY: bytes will be initialized up to and including nul
6409 x.assume_init() == 0
6410 })
6411 .unwrap();
6412 s.increase_len(nul_index);
6413 }
6414 debug_assert_eq!(reserved_ptr, s.as_str().as_ptr());
6415}
6416
6417#[derive(Debug)]
6418pub struct ParseIncomplete {
6419 is_negative: bool,
6420 digits: VecLike<u8>,
6421 radix: i32,
6422}
6423
6424impl Assign<ParseIncomplete> for Integer {
6425 #[inline]
6426 fn assign(&mut self, src: ParseIncomplete) {
6427 // SAFETY: radix is in correct range, and all digits are < radix
6428 unsafe {
6429 self.assign_bytes_radix_unchecked(src.digits.as_slice(), src.radix, src.is_negative);
6430 }
6431 }
6432}
6433
6434from_assign! { ParseIncomplete => Integer }
6435
6436fn parse(bytes: &[u8], radix: i32) -> Result<ParseIncomplete, ParseIntegerError> {
6437 use self::{ParseErrorKind as Kind, ParseIntegerError as Error};
6438
6439 assert!((2..=36).contains(&radix), "radix out of range");
6440 let bradix = radix.unwrapped_as::<u8>();
6441
6442 let mut digits = VecLike::new();
6443 digits.reserve(bytes.len());
6444 let mut has_sign = false;
6445 let mut is_negative = false;
6446 let mut has_digits = false;
6447 for &b in bytes {
6448 let digit = match b {
6449 b'+' if !has_sign && !has_digits => {
6450 has_sign = true;
6451 continue;
6452 }
6453 b'-' if !has_sign && !has_digits => {
6454 is_negative = true;
6455 has_sign = true;
6456 continue;
6457 }
6458 b'_' if has_digits => continue,
6459 b' ' | b'\t' | b'\n' | 0x0b | 0x0c | 0x0d => continue,
6460
6461 b'0'..=b'9' => b - b'0',
6462 b'a'..=b'z' => b - b'a' + 10,
6463 b'A'..=b'Z' => b - b'A' + 10,
6464
6465 // error
6466 _ => bradix,
6467 };
6468 if digit >= bradix {
6469 return Err(Error {
6470 kind: Kind::InvalidDigit,
6471 });
6472 };
6473 has_digits = true;
6474 if digit > 0 || !digits.as_slice().is_empty() {
6475 digits.push(digit);
6476 }
6477 }
6478 if !has_digits {
6479 return Err(Error {
6480 kind: Kind::NoDigits,
6481 });
6482 }
6483 Ok(ParseIncomplete {
6484 is_negative,
6485 digits,
6486 radix,
6487 })
6488}
6489
6490/**
6491An error which can be returned when parsing an [`Integer`].
6492
6493See the <code>[Integer]::[parse\_radix][Integer::parse_radix]</code> method for
6494details on what strings are accepted.
6495
6496# Examples
6497
6498```rust
6499use rug::integer::ParseIntegerError;
6500use rug::Integer;
6501// This string is not an integer.
6502let s = "something completely different (_!_!_)";
6503let error: ParseIntegerError = match Integer::parse_radix(s, 4) {
6504 Ok(_) => unreachable!(),
6505 Err(error) => error,
6506};
6507println!("Parse error: {}", error);
6508```
6509*/
6510#[derive(Clone, Copy, Debug, Eq, PartialEq)]
6511pub struct ParseIntegerError {
6512 kind: ParseErrorKind,
6513}
6514
6515#[derive(Clone, Copy, Debug, Eq, PartialEq)]
6516enum ParseErrorKind {
6517 InvalidDigit,
6518 NoDigits,
6519}
6520
6521impl ParseIntegerError {
6522 fn desc(&self) -> &str {
6523 use self::ParseErrorKind::*;
6524 match self.kind {
6525 InvalidDigit => "invalid digit found in string",
6526 NoDigits => "string has no digits",
6527 }
6528 }
6529}
6530
6531impl Display for ParseIntegerError {
6532 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
6533 Display::fmt(self.desc(), f)
6534 }
6535}
6536
6537#[cfg(feature = "std")]
6538impl Error for ParseIntegerError {
6539 #[allow(deprecated)]
6540 fn description(&self) -> &str {
6541 self.desc()
6542 }
6543}
6544
6545#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
6546/**
6547Whether a number is prime.
6548
6549See the
6550<code>[Integer]::[is\_probably\_prime][Integer::is_probably_prime]</code>
6551method.
6552
6553# Examples
6554
6555```rust
6556use rug::integer::IsPrime;
6557use rug::Integer;
6558let no = Integer::from(163 * 4003);
6559assert_eq!(no.is_probably_prime(30), IsPrime::No);
6560let yes = Integer::from(817_504_243);
6561assert_eq!(yes.is_probably_prime(30), IsPrime::Yes);
6562// 16_412_292_043_871_650_369 is actually a prime.
6563let probably = Integer::from(16_412_292_043_871_650_369_u64);
6564assert_eq!(probably.is_probably_prime(30), IsPrime::Probably);
6565```
6566*/
6567pub enum IsPrime {
6568 /// The number is definitely not prime.
6569 No,
6570 /// The number is probably prime.
6571 Probably,
6572 /// The number is definitely prime.
6573 Yes,
6574}
6575
6576/// Conversions between [`Integer`] and a [slice] of digits of this
6577/// type are provided.
6578///
6579/// For conversion from digits to [`Integer`], see
6580/// <code>[Integer]::[from\_digits][Integer::from_digits]</code>
6581/// and
6582/// <code>[Integer]::[assign\_digits][Integer::assign_digits]</code>.
6583/// For conversion from [`Integer`] to digits, see
6584/// <code>[Integer]::[significant\_digits][Integer::significant_digits]</code>,
6585/// <code>[Integer]::[to\_digits][Integer::to_digits]</code>, and
6586/// <code>[Integer]::[write\_digits][Integer::write_digits]</code>.
6587///
6588/// This trait is sealed and cannot be implemented for more types; it
6589/// is implemented for [`bool`] and the unsigned integer types [`u8`],
6590/// [`u16`], [`u32`], [`u64`], [`u128`] and [`usize`].
6591///
6592/// [slice]: prim@slice
6593pub trait UnsignedPrimitive: SealedUnsignedPrimitive {}
6594
6595pub struct PrivateUnsignedPrimitive {
6596 bytes: usize,
6597 bits: usize,
6598 nails: usize,
6599}
6600
6601/// # Safety
6602///
6603/// Bit patterns can be written to the implementing type. Implementations must
6604/// make sure that all bit patterns are allowed.
6605pub unsafe trait SealedUnsignedPrimitive: Sized {
6606 const PRIVATE: PrivateUnsignedPrimitive = PrivateUnsignedPrimitive {
6607 bytes: mem::size_of::<Self>(),
6608 bits: mem::size_of::<Self>() * 8,
6609 nails: 0,
6610 };
6611}
6612
6613// Safety: We set nails to 7 so that only 0 or 1 can be written into bool.
6614impl UnsignedPrimitive for bool {}
6615unsafe impl SealedUnsignedPrimitive for bool {
6616 const PRIVATE: PrivateUnsignedPrimitive = PrivateUnsignedPrimitive {
6617 bytes: mem::size_of::<Self>(),
6618 bits: 1,
6619 nails: mem::size_of::<Self>() * 8 - 1,
6620 };
6621}
6622
6623impl UnsignedPrimitive for u8 {}
6624unsafe impl SealedUnsignedPrimitive for u8 {}
6625
6626impl UnsignedPrimitive for u16 {}
6627unsafe impl SealedUnsignedPrimitive for u16 {}
6628
6629impl UnsignedPrimitive for u32 {}
6630unsafe impl SealedUnsignedPrimitive for u32 {}
6631
6632impl UnsignedPrimitive for u64 {}
6633unsafe impl SealedUnsignedPrimitive for u64 {}
6634
6635impl UnsignedPrimitive for u128 {}
6636unsafe impl SealedUnsignedPrimitive for u128 {}
6637
6638impl UnsignedPrimitive for usize {}
6639unsafe impl SealedUnsignedPrimitive for usize {}