num-bigint-dig-0.8.2/.cargo_vcs_info.json0000644000000001360000000000100136550ustar { "git": { "sha1": "075cf5777dd157d4ede3062631afa42fbe82ad2b" }, "path_in_vcs": "" }num-bigint-dig-0.8.2/.gitignore000064400000000000000000000000361046102023000144340ustar 00000000000000Cargo.lock target *.bk *.orig num-bigint-dig-0.8.2/.travis.yml000064400000000000000000000003671046102023000145640ustar 00000000000000language: rust rust: - 1.56.0 - stable - beta - nightly sudo: false script: - cargo build --verbose - ./ci/test_full.sh notifications: email: on_success: never branches: only: - master - next - staging - trying num-bigint-dig-0.8.2/Cargo.toml0000644000000050210000000000100116510ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.56" name = "num-bigint-dig" version = "0.8.2" authors = [ "dignifiedquire ", "The Rust Project Developers", ] build = "build.rs" autobenches = false description = "Big integer implementation for Rust" homepage = "https://github.com/dignifiedquire/num-bigint" documentation = "https://docs.rs/num-bigint-dig" readme = "README.md" keywords = [ "mathematics", "numerics", "bignum", ] categories = [ "algorithms", "data-structures", "science", ] license = "MIT/Apache-2.0" repository = "https://github.com/dignifiedquire/num-bigint" [package.metadata.docs.rs] features = [ "std", "serde", "rand", "prime", ] [dependencies.arbitrary] version = "1.1.0" optional = true [dependencies.byteorder] version = "1.2.7" default-features = false [dependencies.lazy_static] version = "1.2.0" features = ["spin_no_std"] default-features = false [dependencies.libm] version = "0.2.1" [dependencies.num-integer] version = "0.1.39" features = ["i128"] default-features = false [dependencies.num-iter] version = "0.1.37" default-features = false [dependencies.num-traits] version = "0.2.4" features = ["i128"] default-features = false [dependencies.rand] version = "0.8.3" optional = true default-features = false [dependencies.serde] version = "1.0" features = ["alloc"] optional = true default-features = false [dependencies.smallvec] version = "1.10.0" default-features = false [dependencies.zeroize] version = "1.5" optional = true default-features = false [dev-dependencies.rand] version = "0.8" features = ["small_rng"] [dev-dependencies.rand_chacha] version = "0.3" [dev-dependencies.rand_isaac] version = "0.3" [dev-dependencies.rand_xorshift] version = "0.3" [dev-dependencies.serde_test] version = "1.0" [features] default = [ "std", "u64_digit", ] fuzz = [ "arbitrary", "smallvec/arbitrary", ] i128 = [] nightly = [] prime = ["rand/std_rng"] std = [ "num-integer/std", "num-traits/std", "smallvec/write", "rand/std", "serde/std", ] u64_digit = [] num-bigint-dig-0.8.2/Cargo.toml.orig000064400000000000000000000040571046102023000153420ustar 00000000000000[package] authors = [ "dignifiedquire ", "The Rust Project Developers" ] description = "Big integer implementation for Rust" documentation = "https://docs.rs/num-bigint-dig" homepage = "https://github.com/dignifiedquire/num-bigint" keywords = ["mathematics", "numerics", "bignum"] categories = ["algorithms", "data-structures", "science"] license = "MIT/Apache-2.0" name = "num-bigint-dig" repository = "https://github.com/dignifiedquire/num-bigint" version = "0.8.2" edition = "2021" rust-version = "1.56" readme = "README.md" build = "build.rs" autobenches = false [package.metadata.docs.rs] features = ["std", "serde", "rand", "prime"] [dependencies.arbitrary] version = "1.1.0" optional = true [dependencies.smallvec] version = "1.10.0" default-features = false [dependencies.num-integer] version = "0.1.39" default-features = false features = [ "i128" ] [dependencies.num-traits] version = "0.2.4" default-features = false features = [ "i128" ] [dependencies.num-iter] version = "0.1.37" default-features = false [dependencies.rand] optional = true version = "0.8.3" default-features = false [dependencies.zeroize] version = "1.5" default-features = false optional = true [dependencies.serde] optional = true version = "1.0" default-features = false features = [ "alloc" ] [dependencies.libm] version = "0.2.1" [dependencies.lazy_static] version = "1.2.0" default-features = false # no_std feature is an anti-pattern. Why, lazy_static, why? # See https://github.com/rust-lang-nursery/lazy-static.rs/issues/150 features = ["spin_no_std"] [dependencies.byteorder] version = "1.2.7" default-features = false [dev-dependencies] rand_chacha = "0.3" rand_xorshift = "0.3" rand_isaac = "0.3" rand = { version = "0.8", features = ["small_rng"] } [dev-dependencies.serde_test] version = "1.0" [features] default = ["std", "u64_digit"] fuzz = ["arbitrary", "smallvec/arbitrary"] i128 = [] std = [ "num-integer/std", "num-traits/std", "smallvec/write", "rand/std", "serde/std" ] u64_digit = [] prime = ["rand/std_rng"] nightly = [] num-bigint-dig-0.8.2/LICENSE-APACHE000064400000000000000000000251371046102023000144010ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. num-bigint-dig-0.8.2/LICENSE-MIT000064400000000000000000000020571046102023000141050ustar 00000000000000Copyright (c) 2014 The Rust Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. num-bigint-dig-0.8.2/README.md000064400000000000000000000060351046102023000137300ustar 00000000000000# num-bigint-dig [![crate](https://img.shields.io/crates/v/num-bigint-dig.svg)](https://crates.io/crates/num-bigint-dig) [![documentation](https://docs.rs/num-bigint-dig/badge.svg)](https://docs.rs/num-bigint-dig) ![minimum rustc 1.56](https://img.shields.io/badge/rustc-1.56+-red.svg) [![Travis status](https://travis-ci.org/dignifiedquire/num-bigint.svg?branch=master)](https://travis-ci.org/dignifiedquire/num-bigint) Big integer types for Rust, `BigInt` and `BigUint`. > **Warning** This is a fork of [`rust-num/num-bigint`](https://github.com/rust-num/num-bigint) with a focus on providing functionality, needed to implement cryptographic operations. ## Usage Add this to your `Cargo.toml`: ```toml [dependencies] num-bigint-dig = "^0.7" ``` and this to your crate root: ```rust extern crate num_bigint_dig as num_bigint; ``` ## Features The `std` feature is enabled by default and mandatory to compile on older rust version. It is possible to use this crate on no_std target. If you wish to compile for a target that does not have an `std` crate, you should use `num-bigint` with `default-features = false`. All other sub-features should be compatible with no_std. Note that in this mode, `num-bigint` still relies on the alloc crate, so make sure you define a `global_allocator`. Implementations for `i128` and `u128` are only available with Rust 1.26 and later. The build script automatically detects this, but you can make it mandatory by enabling the `i128` crate feature. The `u64_digit` feature enables usage of larger internal "digits" (or otherwise known as "limbs"). Speeeding up almost all operations on architectures that have native support for it. The `prime` feature gate enables algorithms and support for dealing with large primes. ## Releases Release notes are available in [RELEASES.md](RELEASES.md). ## Compatibility The `num-bigint` crate is tested for rustc 1.56 and greater. ## Alternatives While `num-bigint` strives for good performance in pure Rust code, other crates may offer better performance with different trade-offs. The following table offers a brief comparison to a few alternatives. | Crate | License | Min rustc | Implementation | | :------------------- | :------------- |:----------| :------------- | | **`num-bigint-dig`** | MIT/Apache-2.0 | 1.56 | pure rust | | [`num-bigint`] | MIT/Apache-2.0 | 1.15 | pure rust | | [`ramp`] | Apache-2.0 | nightly | rust and inline assembly | | [`rug`] | LGPL-3.0+ | 1.18 | bundles [GMP] via [`gmp-mpfr-sys`] | | [`rust-gmp`] | MIT | stable? | links to [GMP] | | [`apint`] | MIT/Apache-2.0 | 1.26 | pure rust (unfinished) | [`num-bigint`]: https://crates.io/crates/num-bigint [GMP]: https://gmplib.org/ [`gmp-mpfr-sys`]: https://crates.io/crates/gmp-mpfr-sys [`rug`]: https://crates.io/crates/rug [`rust-gmp`]: https://crates.io/crates/rust-gmp [`ramp`]: https://crates.io/crates/ramp [`apint`]: https://crates.io/crates/apint ## Benchmarks ``` cargo bench --features prime ``` num-bigint-dig-0.8.2/RELEASES.md000064400000000000000000000123631046102023000141770ustar 00000000000000# Release 0.2.2 (2018-12-14) - [The `Roots` implementations now use better initial guesses][71]. - [Fixed `to_signed_bytes_*` for some positive numbers][72], where the most-significant byte is `0x80` and the rest are `0`. [71]: https://github.com/rust-num/num-bigint/pull/71 [72]: https://github.com/rust-num/num-bigint/pull/72 **Contributors**: @cuviper, @leodasvacas # Release 0.2.1 (2018-11-02) - [`RandBigInt` now uses `Rng::fill_bytes`][53] to improve performance, instead of repeated `gen::` calls. The also affects the implementations of the other `rand` traits. This may potentially change the values produced by some seeded RNGs on previous versions, but the values were tested to be stable with `ChaChaRng`, `IsaacRng`, and `XorShiftRng`. - [`BigInt` and `BigUint` now implement `num_integer::Roots`][56]. - [`BigInt` and `BigUint` now implement `num_traits::Pow`][54]. - [`BigInt` and `BigUint` now implement operators with 128-bit integers][64]. **Contributors**: @cuviper, @dignifiedquire, @mancabizjak, @Robbepop, @TheIronBorn, @thomwiggers [53]: https://github.com/rust-num/num-bigint/pull/53 [54]: https://github.com/rust-num/num-bigint/pull/54 [56]: https://github.com/rust-num/num-bigint/pull/56 [64]: https://github.com/rust-num/num-bigint/pull/64 # Release 0.2.0 (2018-05-25) ### Enhancements - [`BigInt` and `BigUint` now implement `Product` and `Sum`][22] for iterators of any item that we can `Mul` and `Add`, respectively. For example, a factorial can now be simply: `let f: BigUint = (1u32..1000).product();` - [`BigInt` now supports two's-complement logic operations][26], namely `BitAnd`, `BitOr`, `BitXor`, and `Not`. These act conceptually as if each number had an infinite prefix of `0` or `1` bits for positive or negative. - [`BigInt` now supports assignment operators][41] like `AddAssign`. - [`BigInt` and `BigUint` now support conversions with `i128` and `u128`][44], if sufficient compiler support is detected. - [`BigInt` and `BigUint` now implement rand's `SampleUniform` trait][48], and [a custom `RandomBits` distribution samples by bit size][49]. - The release also includes other miscellaneous improvements to performance. ### Breaking Changes - [`num-bigint` now requires rustc 1.15 or greater][23]. - [The crate now has a `std` feature, and won't build without it][46]. This is in preparation for someday supporting `#![no_std]` with `alloc`. - [The `serde` dependency has been updated to 1.0][24], still disabled by default. The `rustc-serialize` crate is no longer supported by `num-bigint`. - [The `rand` dependency has been updated to 0.5][48], now disabled by default. This requires rustc 1.22 or greater for `rand`'s own requirement. - [`Shr for BigInt` now rounds down][8] rather than toward zero, matching the behavior of the primitive integers for negative values. - [`ParseBigIntError` is now an opaque type][37]. - [The `big_digit` module is no longer public][38], nor are the `BigDigit` and `DoubleBigDigit` types and `ZERO_BIG_DIGIT` constant that were re-exported in the crate root. Public APIs which deal in digits, like `BigUint::from_slice`, will now always be base-`u32`. **Contributors**: @clarcharr, @cuviper, @dodomorandi, @tiehuis, @tspiteri [8]: https://github.com/rust-num/num-bigint/pull/8 [22]: https://github.com/rust-num/num-bigint/pull/22 [23]: https://github.com/rust-num/num-bigint/pull/23 [24]: https://github.com/rust-num/num-bigint/pull/24 [26]: https://github.com/rust-num/num-bigint/pull/26 [37]: https://github.com/rust-num/num-bigint/pull/37 [38]: https://github.com/rust-num/num-bigint/pull/38 [41]: https://github.com/rust-num/num-bigint/pull/41 [44]: https://github.com/rust-num/num-bigint/pull/44 [46]: https://github.com/rust-num/num-bigint/pull/46 [48]: https://github.com/rust-num/num-bigint/pull/48 [49]: https://github.com/rust-num/num-bigint/pull/49 # Release 0.1.44 (2018-05-14) - [Division with single-digit divisors is now much faster.][42] - The README now compares [`ramp`, `rug`, `rust-gmp`][20], and [`apint`][21]. **Contributors**: @cuviper, @Robbepop [20]: https://github.com/rust-num/num-bigint/pull/20 [21]: https://github.com/rust-num/num-bigint/pull/21 [42]: https://github.com/rust-num/num-bigint/pull/42 # Release 0.1.43 (2018-02-08) - [The new `BigInt::modpow`][18] performs signed modular exponentiation, using the existing `BigUint::modpow` and rounding negatives similar to `mod_floor`. **Contributors**: @cuviper [18]: https://github.com/rust-num/num-bigint/pull/18 # Release 0.1.42 (2018-02-07) - [num-bigint now has its own source repository][num-356] at [rust-num/num-bigint][home]. - [`lcm` now avoids creating a large intermediate product][num-350]. - [`gcd` now uses Stein's algorithm][15] with faster shifts instead of division. - [`rand` support is now extended to 0.4][11] (while still allowing 0.3). **Contributors**: @cuviper, @Emerentius, @ignatenkobrain, @mhogrefe [home]: https://github.com/rust-num/num-bigint [num-350]: https://github.com/rust-num/num/pull/350 [num-356]: https://github.com/rust-num/num/pull/356 [11]: https://github.com/rust-num/num-bigint/pull/11 [15]: https://github.com/rust-num/num-bigint/pull/15 # Prior releases No prior release notes were kept. Thanks all the same to the many contributors that have made this crate what it is! num-bigint-dig-0.8.2/build.rs000064400000000000000000000000701046102023000141070ustar 00000000000000fn main() { println!("cargo:rustc-cfg=has_i128"); } num-bigint-dig-0.8.2/ci/rustup.sh000075500000000000000000000005461046102023000147460ustar 00000000000000#!/bin/sh # Use rustup to locally run the same suite of tests as .travis.yml. # (You should first install/update all versions listed below.) set -ex export TRAVIS_RUST_VERSION for TRAVIS_RUST_VERSION in 1.15.0 1.22.0 1.26.0 stable beta nightly; do run="rustup run $TRAVIS_RUST_VERSION" $run cargo build --verbose $run $PWD/ci/test_full.sh done num-bigint-dig-0.8.2/ci/test_full.sh000075500000000000000000000030131046102023000153750ustar 00000000000000#!/bin/bash set -ex echo Testing num-bigint on rustc ${TRAVIS_RUST_VERSION} FEATURES="serde i128 u64_digit prime" export RUST_BACKTRACE=1 # num-bigint should build and test everywhere. cargo build --verbose cargo test --verbose # It should build with minimal features too. cargo build --no-default-features --features="std" cargo test --no-default-features --features="std" # It should build in no_std if [[ "$TRAVIS_RUST_VERSION" == "nightly" ]]; then rustup target add thumbv7m-none-eabi cargo build --no-default-features --target=thumbv7m-none-eabi # It should work in no_std on nightly. # Note: Doctest might show an error: https://github.com/rust-lang/rust/issues/54010 # The "error" is wrong however, the doctests still run. cargo test --no-default-features fi # Each isolated feature should also work everywhere. for feature in $FEATURES; do cargo build --verbose --no-default-features --features="std $feature" cargo test --verbose --no-default-features --features="std $feature" # Ensure that feature also works in nostd context on nightly. if [[ "$TRAVIS_RUST_VERSION" == "nightly" ]]; then cargo build --verbose --no-default-features --features="$feature" cargo test --verbose --no-default-features --features="$feature" fi done # test all supported features together cargo build --features="std $FEATURES" cargo test --features="std $FEATURES" # make sure benchmarks can be built if [[ "$TRAVIS_RUST_VERSION" == "nightly" ]]; then cd benchmark_crate cargo bench --all-features --no-run fi num-bigint-dig-0.8.2/src/algorithms/add.rs000064400000000000000000000021331046102023000165020ustar 00000000000000use crate::big_digit::{BigDigit, DoubleBigDigit, BITS}; // Add with carry: #[inline] pub fn adc(a: BigDigit, b: BigDigit, acc: &mut DoubleBigDigit) -> BigDigit { *acc += a as DoubleBigDigit; *acc += b as DoubleBigDigit; let lo = *acc as BigDigit; *acc >>= BITS; lo } // Only for the Add impl: #[inline] pub fn __add2(a: &mut [BigDigit], b: &[BigDigit]) -> BigDigit { debug_assert!(a.len() >= b.len()); let mut carry = 0; let (a_lo, a_hi) = a.split_at_mut(b.len()); for (a, b) in a_lo.iter_mut().zip(b) { *a = adc(*a, *b, &mut carry); } if carry != 0 { for a in a_hi { *a = adc(*a, 0, &mut carry); if carry == 0 { break; } } } carry as BigDigit } /// /Two argument addition of raw slices: /// a += b /// /// The caller _must_ ensure that a is big enough to store the result - typically this means /// resizing a to max(a.len(), b.len()) + 1, to fit a possible carry. pub fn add2(a: &mut [BigDigit], b: &[BigDigit]) { let carry = __add2(a, b); debug_assert!(carry == 0); } num-bigint-dig-0.8.2/src/algorithms/bits.rs000064400000000000000000000007051046102023000167160ustar 00000000000000use core::mem; /// Find last set bit /// fls(0) == 0, fls(u32::MAX) == 32 pub fn fls(v: T) -> usize { mem::size_of::() * 8 - v.leading_zeros() as usize } pub fn ilog2(v: T) -> usize { fls(v) - 1 } /// Divide two integers, and ceil the result. pub fn idiv_ceil(a: T, b: T) -> T { if a % b != T::zero() { a / b + T::one() } else { a / b } } num-bigint-dig-0.8.2/src/algorithms/cmp.rs000064400000000000000000000023121046102023000165300ustar 00000000000000use core::cmp::Ordering::{self, Equal, Greater, Less}; use crate::big_digit::BigDigit; pub fn cmp_slice(a: &[BigDigit], b: &[BigDigit]) -> Ordering { debug_assert!(a.last() != Some(&0)); debug_assert!(b.last() != Some(&0)); let (a_len, b_len) = (a.len(), b.len()); if a_len < b_len { return Less; } if a_len > b_len { return Greater; } for (&ai, &bi) in a.iter().rev().zip(b.iter().rev()) { if ai < bi { return Less; } if ai > bi { return Greater; } } Equal } #[cfg(test)] mod tests { use crate::BigUint; use num_traits::Num; #[test] fn test_eq() { let a = BigUint::from_str_radix("265252859812191058636308480000000", 10).unwrap(); let b = BigUint::from_str_radix("26525285981219105863630848000000", 10).unwrap(); assert!(a != b); assert_ne!(a, b); let a = BigUint::from_str_radix("138995801145388806366366393471481216294", 10).unwrap(); let b = BigUint::from_str_radix("168653801169012228514850424976871974699", 10).unwrap(); assert!(a != b); assert_ne!(a, b); assert!(&a != &b); assert_ne!(&a, &b); } } num-bigint-dig-0.8.2/src/algorithms/div.rs000064400000000000000000000112461046102023000165410ustar 00000000000000use core::cmp::Ordering; use num_traits::{One, Zero}; use smallvec::SmallVec; use crate::algorithms::{add2, cmp_slice, sub2}; use crate::big_digit::{self, BigDigit, DoubleBigDigit}; use crate::BigUint; pub fn div_rem_digit(mut a: BigUint, b: BigDigit) -> (BigUint, BigDigit) { let mut rem = 0; for d in a.data.iter_mut().rev() { let (q, r) = div_wide(rem, *d, b); *d = q; rem = r; } (a.normalized(), rem) } /// Divide a two digit numerator by a one digit divisor, returns quotient and remainder: /// /// Note: the caller must ensure that both the quotient and remainder will fit into a single digit. /// This is _not_ true for an arbitrary numerator/denominator. /// /// (This function also matches what the x86 divide instruction does). #[inline] pub fn div_wide(hi: BigDigit, lo: BigDigit, divisor: BigDigit) -> (BigDigit, BigDigit) { debug_assert!(hi < divisor); let lhs = big_digit::to_doublebigdigit(hi, lo); let rhs = divisor as DoubleBigDigit; ((lhs / rhs) as BigDigit, (lhs % rhs) as BigDigit) } pub fn div_rem(u: &BigUint, d: &BigUint) -> (BigUint, BigUint) { if d.is_zero() { panic!() } if u.is_zero() { return (Zero::zero(), Zero::zero()); } if d.data.len() == 1 { if d.data[0] == 1 { return (u.clone(), Zero::zero()); } let (div, rem) = div_rem_digit(u.clone(), d.data[0]); return (div, rem.into()); } // Required or the q_len calculation below can underflow: match u.cmp(d) { Ordering::Less => return (Zero::zero(), u.clone()), Ordering::Equal => return (One::one(), Zero::zero()), Ordering::Greater => {} // Do nothing } // This algorithm is from Knuth, TAOCP vol 2 section 4.3, algorithm D: // // First, normalize the arguments so the highest bit in the highest digit of the divisor is // set: the main loop uses the highest digit of the divisor for generating guesses, so we // want it to be the largest number we can efficiently divide by. // let shift = d.data.last().unwrap().leading_zeros() as usize; let mut a = u << shift; let b = d << shift; // The algorithm works by incrementally calculating "guesses", q0, for part of the // remainder. Once we have any number q0 such that q0 * b <= a, we can set // // q += q0 // a -= q0 * b // // and then iterate until a < b. Then, (q, a) will be our desired quotient and remainder. // // q0, our guess, is calculated by dividing the last few digits of a by the last digit of b // - this should give us a guess that is "close" to the actual quotient, but is possibly // greater than the actual quotient. If q0 * b > a, we simply use iterated subtraction // until we have a guess such that q0 * b <= a. // let bn = *b.data.last().unwrap(); let q_len = a.data.len() - b.data.len() + 1; let mut q = BigUint { data: smallvec![0; q_len], }; // We reuse the same temporary to avoid hitting the allocator in our inner loop - this is // sized to hold a0 (in the common case; if a particular digit of the quotient is zero a0 // can be bigger). // let mut tmp = BigUint { data: SmallVec::with_capacity(2), }; for j in (0..q_len).rev() { /* * When calculating our next guess q0, we don't need to consider the digits below j * + b.data.len() - 1: we're guessing digit j of the quotient (i.e. q0 << j) from * digit bn of the divisor (i.e. bn << (b.data.len() - 1) - so the product of those * two numbers will be zero in all digits up to (j + b.data.len() - 1). */ let offset = j + b.data.len() - 1; if offset >= a.data.len() { continue; } /* just avoiding a heap allocation: */ let mut a0 = tmp; a0.data.truncate(0); a0.data.extend(a.data[offset..].iter().cloned()); /* * q0 << j * big_digit::BITS is our actual quotient estimate - we do the shifts * implicitly at the end, when adding and subtracting to a and q. Not only do we * save the cost of the shifts, the rest of the arithmetic gets to work with * smaller numbers. */ let (mut q0, _) = div_rem_digit(a0, bn); let mut prod = &b * &q0; while cmp_slice(&prod.data[..], &a.data[j..]) == Ordering::Greater { let one: BigUint = One::one(); q0 = q0 - one; prod = prod - &b; } add2(&mut q.data[j..], &q0.data[..]); sub2(&mut a.data[j..], &prod.data[..]); a.normalize(); tmp = q0; } debug_assert!(a < b); (q.normalized(), a >> shift) } num-bigint-dig-0.8.2/src/algorithms/gcd.rs000064400000000000000000000545101046102023000165150ustar 00000000000000use crate::big_digit::{BigDigit, DoubleBigDigit, BITS}; use crate::bigint::Sign::*; use crate::bigint::{BigInt, ToBigInt}; use crate::biguint::{BigUint, IntDigits}; use crate::integer::Integer; use alloc::borrow::Cow; use core::ops::Neg; use num_traits::{One, Signed, Zero}; /// XGCD sets z to the greatest common divisor of a and b and returns z. /// If extended is true, XGCD returns their value such that z = a*x + b*y. /// /// Allow the inputs a and b to be zero or negative to GCD /// with the following definitions. /// /// If x or y are not nil, GCD sets their value such that z = a*x + b*y. /// Regardless of the signs of a and b, z is always >= 0. /// If a == b == 0, GCD sets z = x = y = 0. /// If a == 0 and b != 0, GCD sets z = |b|, x = 0, y = sign(b) * 1. /// If a != 0 and b == 0, GCD sets z = |a|, x = sign(a) * 1, y = 0. pub fn xgcd( a_in: &BigInt, b_in: &BigInt, extended: bool, ) -> (BigInt, Option, Option) { //If a == b == 0, GCD sets z = x = y = 0. if a_in.is_zero() && b_in.is_zero() { if extended { return (0.into(), Some(0.into()), Some(0.into())); } else { return (0.into(), None, None); } } //If a == 0 and b != 0, GCD sets z = |b|, x = 0, y = sign(b) * 1. // if a_in.is_zero() && !b_in.is_zero() { if a_in.is_zero() { if extended { let mut y = BigInt::one(); if b_in.sign == Minus { y.sign = Minus; } return (b_in.abs(), Some(0.into()), Some(y)); } else { return (b_in.abs(), None, None); } } //If a != 0 and b == 0, GCD sets z = |a|, x = sign(a) * 1, y = 0. //if !a_in.is_zero() && b_in.is_zero() { if b_in.is_zero() { if extended { let mut x = BigInt::one(); if a_in.sign == Minus { x.sign = Minus; } return (a_in.abs(), Some(x), Some(0.into())); } else { return (a_in.abs(), None, None); } } lehmer_gcd(a_in, b_in, extended) } /// lehmerGCD sets z to the greatest common divisor of a and b, /// which both must be != 0, and returns z. /// If x or y are not nil, their values are set such that z = a*x + b*y. /// See Knuth, The Art of Computer Programming, Vol. 2, Section 4.5.2, Algorithm L. /// This implementation uses the improved condition by Collins requiring only one /// quotient and avoiding the possibility of single Word overflow. /// See Jebelean, "Improving the multiprecision Euclidean algorithm", /// Design and Implementation of Symbolic Computation Systems, pp 45-58. /// The cosequences are updated according to Algorithm 10.45 from /// Cohen et al. "Handbook of Elliptic and Hyperelliptic Curve Cryptography" pp 192. fn lehmer_gcd( a_in: &BigInt, b_in: &BigInt, extended: bool, ) -> (BigInt, Option, Option) { let mut a = a_in.clone(); let mut b = b_in.clone(); //essential absolute value on both a & b a.sign = Plus; b.sign = Plus; // `ua` (`ub`) tracks how many times input `a_in` has beeen accumulated into `a` (`b`). let mut ua = if extended { Some(1.into()) } else { None }; let mut ub = if extended { Some(0.into()) } else { None }; // temp variables for multiprecision update let mut q: BigInt = 0.into(); let mut r: BigInt = 0.into(); let mut s: BigInt = 0.into(); let mut t: BigInt = 0.into(); // Ensure that a >= b if a < b { core::mem::swap(&mut a, &mut b); core::mem::swap(&mut ua, &mut ub); } // loop invariant A >= B while b.len() > 1 { // Attempt to calculate in single-precision using leading words of a and b. let (u0, u1, v0, v1, even) = lehmer_simulate(&a, &b); // multiprecision step if v0 != 0 { // Simulate the effect of the single-precision steps using cosequences. // a = u0 * a + v0 * b // b = u1 * a + v1 * b lehmer_update( &mut a, &mut b, &mut q, &mut r, &mut s, &mut t, u0, u1, v0, v1, even, ); if extended { // ua = u0 * ua + v0 * ub // ub = u1 * ua + v1 * ub lehmer_update( ua.as_mut().unwrap(), ub.as_mut().unwrap(), &mut q, &mut r, &mut s, &mut t, u0, u1, v0, v1, even, ); } } else { // Single-digit calculations failed to simulate any quotients. euclid_udpate( &mut a, &mut b, &mut ua, &mut ub, &mut q, &mut r, &mut s, &mut t, extended, ); } } if b.len() > 0 { // base case if b is a single digit if a.len() > 1 { // a is longer than a single word, so one update is needed euclid_udpate( &mut a, &mut b, &mut ua, &mut ub, &mut q, &mut r, &mut s, &mut t, extended, ); } if b.len() > 0 { // a and b are both single word let mut a_word = a.digits()[0]; let mut b_word = b.digits()[0]; if extended { let mut ua_word: BigDigit = 1; let mut ub_word: BigDigit = 0; let mut va: BigDigit = 0; let mut vb: BigDigit = 1; let mut even = true; while b_word != 0 { let q = a_word / b_word; let r = a_word % b_word; a_word = b_word; b_word = r; let k = ua_word.wrapping_add(q.wrapping_mul(ub_word)); ua_word = ub_word; ub_word = k; let k = va.wrapping_add(q.wrapping_mul(vb)); va = vb; vb = k; even = !even; } t.data.set_digit(ua_word); s.data.set_digit(va); t.sign = if even { Plus } else { Minus }; s.sign = if even { Minus } else { Plus }; if let Some(ua) = ua.as_mut() { t *= &*ua; s *= ub.unwrap(); *ua = &t + &s; } } else { while b_word != 0 { let quotient = a_word % b_word; a_word = b_word; b_word = quotient; } } a.digits_mut()[0] = a_word; } } a.normalize(); //Sign fixing let mut neg_a: bool = false; if a_in.sign == Minus { neg_a = true; } let y = if let Some(ref mut ua) = ua { // y = (z - a * x) / b //a_in*x let mut tmp = a_in * &*ua; if neg_a { tmp.sign = tmp.sign.neg(); ua.sign = ua.sign.neg(); } //z - (a_in * x) tmp = &a - &tmp; tmp = &tmp / b_in; Some(tmp) } else { None }; a.sign = Plus; (a, ua, y) } /// Uses the lehemer algorithm. /// Based on https://github.com/golang/go/blob/master/src/math/big/int.go#L612 /// If `extended` is set, the Bezout coefficients are calculated, otherwise they are `None`. pub fn extended_gcd( a_in: Cow, b_in: Cow, extended: bool, ) -> (BigInt, Option, Option) { if a_in.is_zero() && b_in.is_zero() { if extended { return (b_in.to_bigint().unwrap(), Some(0.into()), Some(0.into())); } else { return (b_in.to_bigint().unwrap(), None, None); } } if a_in.is_zero() { if extended { return (b_in.to_bigint().unwrap(), Some(0.into()), Some(1.into())); } else { return (b_in.to_bigint().unwrap(), None, None); } } if b_in.is_zero() { if extended { return (a_in.to_bigint().unwrap(), Some(1.into()), Some(0.into())); } else { return (a_in.to_bigint().unwrap(), None, None); } } let a_in = a_in.to_bigint().unwrap(); let b_in = b_in.to_bigint().unwrap(); let mut a = a_in.clone(); let mut b = b_in.clone(); // `ua` (`ub`) tracks how many times input `a_in` has beeen accumulated into `a` (`b`). let mut ua = if extended { Some(1.into()) } else { None }; let mut ub = if extended { Some(0.into()) } else { None }; // Ensure that a >= b if a < b { core::mem::swap(&mut a, &mut b); core::mem::swap(&mut ua, &mut ub); } let mut q: BigInt = 0.into(); let mut r: BigInt = 0.into(); let mut s: BigInt = 0.into(); let mut t: BigInt = 0.into(); while b.len() > 1 { // Attempt to calculate in single-precision using leading words of a and b. let (u0, u1, v0, v1, even) = lehmer_simulate(&a, &b); // multiprecision step if v0 != 0 { // Simulate the effect of the single-precision steps using cosequences. // a = u0 * a + v0 * b // b = u1 * a + v1 * b lehmer_update( &mut a, &mut b, &mut q, &mut r, &mut s, &mut t, u0, u1, v0, v1, even, ); if extended { // ua = u0 * ua + v0 * ub // ub = u1 * ua + v1 * ub lehmer_update( ua.as_mut().unwrap(), ub.as_mut().unwrap(), &mut q, &mut r, &mut s, &mut t, u0, u1, v0, v1, even, ); } } else { // Single-digit calculations failed to simulate any quotients. euclid_udpate( &mut a, &mut b, &mut ua, &mut ub, &mut q, &mut r, &mut s, &mut t, extended, ); } } if b.len() > 0 { // base case if b is a single digit if a.len() > 1 { // a is longer than a single word, so one update is needed euclid_udpate( &mut a, &mut b, &mut ua, &mut ub, &mut q, &mut r, &mut s, &mut t, extended, ); } if b.len() > 0 { // a and b are both single word let mut a_word = a.digits()[0]; let mut b_word = b.digits()[0]; if extended { let mut ua_word: BigDigit = 1; let mut ub_word: BigDigit = 0; let mut va: BigDigit = 0; let mut vb: BigDigit = 1; let mut even = true; while b_word != 0 { let q = a_word / b_word; let r = a_word % b_word; a_word = b_word; b_word = r; let k = ua_word.wrapping_add(q.wrapping_mul(ub_word)); ua_word = ub_word; ub_word = k; let k = va.wrapping_add(q.wrapping_mul(vb)); va = vb; vb = k; even = !even; } t.data.set_digit(ua_word); s.data.set_digit(va); t.sign = if even { Plus } else { Minus }; s.sign = if even { Minus } else { Plus }; if let Some(ua) = ua.as_mut() { t *= &*ua; s *= ub.unwrap(); *ua = &t + &s; } } else { while b_word != 0 { let quotient = a_word % b_word; a_word = b_word; b_word = quotient; } } a.digits_mut()[0] = a_word; } } a.normalize(); let y = if let Some(ref ua) = ua { // y = (z - a * x) / b Some((&a - (&a_in * ua)) / &b_in) } else { None }; (a, ua, y) } /// Attempts to simulate several Euclidean update steps using leading digits of `a` and `b`. /// It returns `u0`, `u1`, `v0`, `v1` such that `a` and `b` can be updated as: /// a = u0 * a + v0 * b /// b = u1 * a + v1 * b /// /// Requirements: `a >= b` and `b.len() > 2`. /// Since we are calculating with full words to avoid overflow, `even` (the returned bool) /// is used to track the sign of cosequences. /// For even iterations: `u0, v1 >= 0 && u1, v0 <= 0` /// For odd iterations: `u0, v1 <= && u1, v0 >= 0` #[inline] fn lehmer_simulate(a: &BigInt, b: &BigInt) -> (BigDigit, BigDigit, BigDigit, BigDigit, bool) { // m >= 2 let m = b.len(); // n >= m >= 2 let n = a.len(); // println!("a len is {:?}", a.len()); // println!("b len is {:?}", b.len()); // debug_assert!(m >= 2); // debug_assert!(n >= m); // extract the top word of bits from a and b let h = a.digits()[n - 1].leading_zeros(); let mut a1: BigDigit = a.digits()[n - 1] << h | ((a.digits()[n - 2] as DoubleBigDigit) >> (BITS as u32 - h)) as BigDigit; // b may have implicit zero words in the high bits if the lengths differ let mut a2: BigDigit = if n == m { b.digits()[n - 1] << h | ((b.digits()[n - 2] as DoubleBigDigit) >> (BITS as u32 - h)) as BigDigit } else if n == m + 1 { ((b.digits()[n - 2] as DoubleBigDigit) >> (BITS as u32 - h)) as BigDigit } else { 0 }; // odd, even tracking let mut even = false; let mut u0 = 0; let mut u1 = 1; let mut u2 = 0; let mut v0 = 0; let mut v1 = 0; let mut v2 = 1; // Calculate the quotient and cosequences using Collins' stoppting condition. while a2 >= v2 && a1.wrapping_sub(a2) >= v1 + v2 { let q = a1 / a2; let r = a1 % a2; a1 = a2; a2 = r; let k = u1 + q * u2; u0 = u1; u1 = u2; u2 = k; let k = v1 + q * v2; v0 = v1; v1 = v2; v2 = k; even = !even; } (u0, u1, v0, v1, even) } fn lehmer_update( a: &mut BigInt, b: &mut BigInt, q: &mut BigInt, r: &mut BigInt, s: &mut BigInt, t: &mut BigInt, u0: BigDigit, u1: BigDigit, v0: BigDigit, v1: BigDigit, even: bool, ) { t.data.set_digit(u0); s.data.set_digit(v0); if even { t.sign = Plus; s.sign = Minus } else { t.sign = Minus; s.sign = Plus; } *t *= &*a; *s *= &*b; r.data.set_digit(u1); q.data.set_digit(v1); if even { q.sign = Plus; r.sign = Minus } else { q.sign = Minus; r.sign = Plus; } *r *= &*a; *q *= &*b; *a = t + s; *b = r + q; } fn euclid_udpate( a: &mut BigInt, b: &mut BigInt, ua: &mut Option, ub: &mut Option, q: &mut BigInt, r: &mut BigInt, s: &mut BigInt, t: &mut BigInt, extended: bool, ) { let (q_new, r_new) = a.div_rem(b); *q = q_new; *r = r_new; core::mem::swap(a, b); core::mem::swap(b, r); if extended { // ua, ub = ub, ua - q * ub if let Some(ub) = ub.as_mut() { if let Some(ua) = ua.as_mut() { *t = ub.clone(); *s = &*ub * &*q; *ub = &*ua - &*s; *ua = t.clone(); } } } } #[cfg(test)] mod tests { use super::*; use core::str::FromStr; use num_traits::FromPrimitive; #[cfg(feature = "rand")] use crate::bigrand::RandBigInt; #[cfg(feature = "rand")] use num_traits::{One, Zero}; #[cfg(feature = "rand")] use rand::SeedableRng; #[cfg(feature = "rand")] use rand_xorshift::XorShiftRng; #[cfg(feature = "rand")] fn extended_gcd_euclid(a: Cow, b: Cow) -> (BigInt, BigInt, BigInt) { // use crate::bigint::ToBigInt; if a.is_zero() && b.is_zero() { return (0.into(), 0.into(), 0.into()); } let (mut s, mut old_s) = (BigInt::zero(), BigInt::one()); let (mut t, mut old_t) = (BigInt::one(), BigInt::zero()); let (mut r, mut old_r) = (b.to_bigint().unwrap(), a.to_bigint().unwrap()); while !r.is_zero() { let quotient = &old_r / &r; old_r = old_r - "ient * &r; core::mem::swap(&mut old_r, &mut r); old_s = old_s - "ient * &s; core::mem::swap(&mut old_s, &mut s); old_t = old_t - quotient * &t; core::mem::swap(&mut old_t, &mut t); } (old_r, old_s, old_t) } #[test] #[cfg(feature = "rand")] fn test_extended_gcd_assumptions() { let mut rng = XorShiftRng::from_seed([1u8; 16]); for i in 1usize..100 { for j in &[1usize, 64, 128] { //println!("round {} - {}", i, j); let a = rng.gen_biguint(i * j); let b = rng.gen_biguint(i * j); let (q, s_k, t_k) = extended_gcd(Cow::Borrowed(&a), Cow::Borrowed(&b), true); let lhs = BigInt::from_biguint(Plus, a) * &s_k.unwrap(); let rhs = BigInt::from_biguint(Plus, b) * &t_k.unwrap(); assert_eq!(q.clone(), &lhs + &rhs, "{} = {} + {}", q, lhs, rhs); } } } #[test] fn test_extended_gcd_example() { // simple example for wikipedia let a = BigUint::from_u32(240).unwrap(); let b = BigUint::from_u32(46).unwrap(); let (q, s_k, t_k) = extended_gcd(Cow::Owned(a), Cow::Owned(b), true); assert_eq!(q, BigInt::from_i32(2).unwrap()); assert_eq!(s_k.unwrap(), BigInt::from_i32(-9).unwrap()); assert_eq!(t_k.unwrap(), BigInt::from_i32(47).unwrap()); } #[test] fn test_extended_gcd_example_not_extended() { // simple example for wikipedia let a = BigUint::from_u32(240).unwrap(); let b = BigUint::from_u32(46).unwrap(); let (q, s_k, t_k) = extended_gcd(Cow::Owned(a), Cow::Owned(b), false); assert_eq!(q, BigInt::from_i32(2).unwrap()); assert_eq!(s_k, None); assert_eq!(t_k, None); } #[test] fn test_extended_gcd_example_wolfram() { // https://www.wolframalpha.com/input/?i=ExtendedGCD%5B-565721958+,+4486780496%5D // https://github.com/Chia-Network/oldvdf-competition/blob/master/tests/test_classgroup.py#L109 let a = BigInt::from_str("-565721958").unwrap(); let b = BigInt::from_str("4486780496").unwrap(); let (q, _s_k, _t_k) = xgcd(&a, &b, true); assert_eq!(q, BigInt::from(2)); assert_eq!(_s_k, Some(BigInt::from(-1090996795))); assert_eq!(_t_k, Some(BigInt::from(-137559848))); } #[test] fn test_golang_bignum_negative() { // a <= 0 || b <= 0 //d, x, y, a, b string let gcd_test_cases = [ ["0", "0", "0", "0", "0"], ["7", "0", "1", "0", "7"], ["7", "0", "-1", "0", "-7"], ["11", "1", "0", "11", "0"], ["7", "-1", "-2", "-77", "35"], ["935", "-3", "8", "64515", "24310"], ["935", "-3", "-8", "64515", "-24310"], ["935", "3", "-8", "-64515", "-24310"], ["1", "-9", "47", "120", "23"], ["7", "1", "-2", "77", "35"], ["935", "-3", "8", "64515", "24310"], [ "935000000000000000", "-3", "8", "64515000000000000000", "24310000000000000000", ], [ "1", "-221", "22059940471369027483332068679400581064239780177629666810348940098015901108344", "98920366548084643601728869055592650835572950932266967461790948584315647051443", "991", ], ]; for t in 0..gcd_test_cases.len() { //d, x, y, a, b string let d_case = BigInt::from_str(gcd_test_cases[t][0]).unwrap(); let x_case = BigInt::from_str(gcd_test_cases[t][1]).unwrap(); let y_case = BigInt::from_str(gcd_test_cases[t][2]).unwrap(); let a_case = BigInt::from_str(gcd_test_cases[t][3]).unwrap(); let b_case = BigInt::from_str(gcd_test_cases[t][4]).unwrap(); // println!("round is {:?}", t); // println!("a len is {:?}", a_case.len()); // println!("b len is {:?}", b_case.len()); // println!("a is {:?}", &a_case); // println!("b is {:?}", &b_case); //testGcd(d, nil, nil, a, b) //testGcd(d, x, y, a, b) let (_d, _x, _y) = xgcd(&a_case, &b_case, false); assert_eq!(_d, d_case); assert_eq!(_x, None); assert_eq!(_y, None); let (_d, _x, _y) = xgcd(&a_case, &b_case, true); assert_eq!(_d, d_case); assert_eq!(_x.unwrap(), x_case); assert_eq!(_y.unwrap(), y_case); } } #[test] #[cfg(feature = "rand")] fn test_gcd_lehmer_euclid_extended() { let mut rng = XorShiftRng::from_seed([1u8; 16]); for i in 1usize..80 { for j in &[1usize, 16, 24, 64, 128] { //println!("round {} - {}", i, j); let a = rng.gen_biguint(i * j); let b = rng.gen_biguint(i * j); let (q, s_k, t_k) = extended_gcd(Cow::Borrowed(&a), Cow::Borrowed(&b), true); let expected = extended_gcd_euclid(Cow::Borrowed(&a), Cow::Borrowed(&b)); assert_eq!(q, expected.0); assert_eq!(s_k.unwrap(), expected.1); assert_eq!(t_k.unwrap(), expected.2); } } } #[test] #[cfg(feature = "rand")] fn test_gcd_lehmer_euclid_not_extended() { let mut rng = XorShiftRng::from_seed([1u8; 16]); for i in 1usize..80 { for j in &[1usize, 16, 24, 64, 128] { //println!("round {} - {}", i, j); let a = rng.gen_biguint(i * j); let b = rng.gen_biguint(i * j); let (q, s_k, t_k) = extended_gcd(Cow::Borrowed(&a), Cow::Borrowed(&b), false); let expected = extended_gcd_euclid(Cow::Borrowed(&a), Cow::Borrowed(&b)); assert_eq!( q, expected.0, "gcd({}, {}) = {} != {}", &a, &b, &q, expected.0 ); assert_eq!(s_k, None); assert_eq!(t_k, None); } } } } num-bigint-dig-0.8.2/src/algorithms/jacobi.rs000064400000000000000000000040331046102023000172020ustar 00000000000000use crate::integer::Integer; use num_traits::{One, Signed, Zero}; use crate::BigInt; /// Jacobi returns the Jacobi symbol (x/y), either +1, -1, or 0. /// The y argument must be an odd integer. pub fn jacobi(x: &BigInt, y: &BigInt) -> isize { if !y.is_odd() { panic!( "invalid arguments, y must be an odd integer,but got {:?}", y ); } let mut a = x.clone(); let mut b = y.clone(); let mut j = 1; if b.is_negative() { if a.is_negative() { j = -1; } b = -b; } loop { if b.is_one() { return j; } if a.is_zero() { return 0; } a = a.mod_floor(&b); if a.is_zero() { return 0; } // a > 0 // handle factors of 2 in a let s = a.trailing_zeros().unwrap(); if s & 1 != 0 { let bmod8 = b.get_limb(0) & 7; if bmod8 == 3 || bmod8 == 5 { j = -j; } } let c = &a >> s; // a = 2^s*c // swap numerator and denominator if b.get_limb(0) & 3 == 3 && c.get_limb(0) & 3 == 3 { j = -j } a = b; b = c; } } #[cfg(test)] mod tests { use super::*; use num_traits::FromPrimitive; use crate::BigInt; #[test] fn test_jacobi() { let cases = [ [0, 1, 1], [0, -1, 1], [1, 1, 1], [1, -1, 1], [0, 5, 0], [1, 5, 1], [2, 5, -1], [-2, 5, -1], [2, -5, -1], [-2, -5, 1], [3, 5, -1], [5, 5, 0], [-5, 5, 0], [6, 5, 1], [6, -5, 1], [-6, 5, 1], [-6, -5, -1], ]; for case in cases.iter() { let x = BigInt::from_i64(case[0]).unwrap(); let y = BigInt::from_i64(case[1]).unwrap(); assert_eq!(case[2] as isize, jacobi(&x, &y), "jacobi({}, {})", x, y); } } } num-bigint-dig-0.8.2/src/algorithms/mac.rs000064400000000000000000001526641046102023000165310ustar 00000000000000use core::cmp; use core::iter::repeat; use crate::algorithms::{adc, add2, sub2, sub_sign}; use crate::big_digit::{BigDigit, DoubleBigDigit, BITS}; use crate::bigint::Sign::{Minus, NoSign, Plus}; use crate::biguint::IntDigits; use crate::{BigInt, BigUint}; #[inline] pub fn mac_with_carry(a: BigDigit, b: BigDigit, c: BigDigit, acc: &mut DoubleBigDigit) -> BigDigit { *acc += a as DoubleBigDigit; *acc += (b as DoubleBigDigit) * (c as DoubleBigDigit); let lo = *acc as BigDigit; *acc >>= BITS; lo } /// Three argument multiply accumulate: /// acc += b * c pub fn mac_digit(acc: &mut [BigDigit], b: &[BigDigit], c: BigDigit) { if c == 0 { return; } let mut carry = 0; let (a_lo, a_hi) = acc.split_at_mut(b.len()); for (a, &b) in a_lo.iter_mut().zip(b) { *a = mac_with_carry(*a, b, c, &mut carry); } let mut a = a_hi.iter_mut(); while carry != 0 { let a = a.next().expect("carry overflow during multiplication!"); *a = adc(*a, 0, &mut carry); } } /// Three argument multiply accumulate: /// acc += b * c pub fn mac3(acc: &mut [BigDigit], b: &[BigDigit], c: &[BigDigit]) { let (x, y) = if b.len() < c.len() { (b, c) } else { (c, b) }; // We use three algorithms for different input sizes. // // - For small inputs, long multiplication is fastest. // - Next we use Karatsuba multiplication (Toom-2), which we have optimized // to avoid unnecessary allocations for intermediate values. // - For the largest inputs we use Toom-3, which better optimizes the // number of operations, but uses more temporary allocations. // // The thresholds are somewhat arbitrary, chosen by evaluating the results // of `cargo bench --bench bigint multiply`. if x.len() <= 32 { long(acc, x, y) } else if x.len() <= 256 { karatsuba(acc, x, y) } else { toom3(acc, x, y) } } /// Long multiplication: fn long(acc: &mut [BigDigit], x: &[BigDigit], y: &[BigDigit]) { for (i, xi) in x.iter().enumerate() { mac_digit(&mut acc[i..], y, *xi); } } /// Karatsuba multiplication: /// /// The idea is that we break x and y up into two smaller numbers that each have about half /// as many digits, like so (note that multiplying by b is just a shift): /// /// x = x0 + x1 * b /// y = y0 + y1 * b /// /// With some algebra, we can compute x * y with three smaller products, where the inputs to /// each of the smaller products have only about half as many digits as x and y: /// /// x * y = (x0 + x1 * b) * (y0 + y1 * b) /// /// x * y = x0 * y0 /// + x0 * y1 * b /// + x1 * y0 * b + x1 * y1 * b^2 /// /// Let p0 = x0 * y0 and p2 = x1 * y1: /// /// x * y = p0 /// + (x0 * y1 + x1 * y0) * b /// + p2 * b^2 /// /// The real trick is that middle term: /// /// x0 * y1 + x1 * y0 /// = x0 * y1 + x1 * y0 - p0 + p0 - p2 + p2 /// = x0 * y1 + x1 * y0 - x0 * y0 - x1 * y1 + p0 + p2 /// /// Now we complete the square: /// /// = -(x0 * y0 - x0 * y1 - x1 * y0 + x1 * y1) + p0 + p2 /// = -((x1 - x0) * (y1 - y0)) + p0 + p2 /// /// Let p1 = (x1 - x0) * (y1 - y0), and substitute back into our original formula: /// /// x * y = p0 /// + (p0 + p2 - p1) * b /// + p2 * b^2 /// /// Where the three intermediate products are: /// /// p0 = x0 * y0 /// p1 = (x1 - x0) * (y1 - y0) /// p2 = x1 * y1 /// /// In doing the computation, we take great care to avoid unnecessary temporary variables /// (since creating a BigUint requires a heap allocation): thus, we rearrange the formula a /// bit so we can use the same temporary variable for all the intermediate products: /// /// x * y = p2 * b^2 + p2 * b /// + p0 * b + p0 /// - p1 * b /// /// The other trick we use is instead of doing explicit shifts, we slice acc at the /// appropriate offset when doing the add. fn karatsuba(acc: &mut [BigDigit], x: &[BigDigit], y: &[BigDigit]) { /* * When x is smaller than y, it's significantly faster to pick b such that x is split in * half, not y: */ let b = x.len() / 2; let (x0, x1) = x.split_at(b); let (y0, y1) = y.split_at(b); /* * We reuse the same BigUint for all the intermediate multiplies and have to size p * appropriately here: x1.len() >= x0.len and y1.len() >= y0.len(): */ let len = x1.len() + y1.len() + 1; let mut p = BigUint { data: smallvec![0; len], }; // p2 = x1 * y1 mac3(&mut p.data[..], x1, y1); // Not required, but the adds go faster if we drop any unneeded 0s from the end: p.normalize(); add2(&mut acc[b..], &p.data[..]); add2(&mut acc[b * 2..], &p.data[..]); // Zero out p before the next multiply: p.data.truncate(0); p.data.extend(repeat(0).take(len)); // p0 = x0 * y0 mac3(&mut p.data[..], x0, y0); p.normalize(); add2(&mut acc[..], &p.data[..]); add2(&mut acc[b..], &p.data[..]); // p1 = (x1 - x0) * (y1 - y0) // We do this one last, since it may be negative and acc can't ever be negative: let (j0_sign, j0) = sub_sign(x1, x0); let (j1_sign, j1) = sub_sign(y1, y0); match j0_sign * j1_sign { Plus => { p.data.truncate(0); p.data.extend(repeat(0).take(len)); mac3(&mut p.data[..], &j0.data[..], &j1.data[..]); p.normalize(); sub2(&mut acc[b..], &p.data[..]); } Minus => { mac3(&mut acc[b..], &j0.data[..], &j1.data[..]); } NoSign => (), } } /// Toom-3 multiplication: /// /// Toom-3 is like Karatsuba above, but dividing the inputs into three parts. /// Both are instances of Toom-Cook, using `k=3` and `k=2` respectively. /// /// The general idea is to treat the large integers digits as /// polynomials of a certain degree and determine the coefficients/digits /// of the product of the two via interpolation of the polynomial product. fn toom3(acc: &mut [BigDigit], x: &[BigDigit], y: &[BigDigit]) { let i = y.len() / 3 + 1; let x0_len = cmp::min(x.len(), i); let x1_len = cmp::min(x.len() - x0_len, i); let y0_len = i; let y1_len = cmp::min(y.len() - y0_len, i); // Break x and y into three parts, representating an order two polynomial. // t is chosen to be the size of a digit so we can use faster shifts // in place of multiplications. // // x(t) = x2*t^2 + x1*t + x0 let x0 = BigInt::from_slice_native(Plus, &x[..x0_len]); let x1 = BigInt::from_slice_native(Plus, &x[x0_len..x0_len + x1_len]); let x2 = BigInt::from_slice_native(Plus, &x[x0_len + x1_len..]); // y(t) = y2*t^2 + y1*t + y0 let y0 = BigInt::from_slice_native(Plus, &y[..y0_len]); let y1 = BigInt::from_slice_native(Plus, &y[y0_len..y0_len + y1_len]); let y2 = BigInt::from_slice_native(Plus, &y[y0_len + y1_len..]); // Let w(t) = x(t) * y(t) // // This gives us the following order-4 polynomial. // // w(t) = w4*t^4 + w3*t^3 + w2*t^2 + w1*t + w0 // // We need to find the coefficients w4, w3, w2, w1 and w0. Instead // of simply multiplying the x and y in total, we can evaluate w // at 5 points. An n-degree polynomial is uniquely identified by (n + 1) // points. // // It is arbitrary as to what points we evaluate w at but we use the // following. // // w(t) at t = 0, 1, -1, -2 and inf // // The values for w(t) in terms of x(t)*y(t) at these points are: // // let a = w(0) = x0 * y0 // let b = w(1) = (x2 + x1 + x0) * (y2 + y1 + y0) // let c = w(-1) = (x2 - x1 + x0) * (y2 - y1 + y0) // let d = w(-2) = (4*x2 - 2*x1 + x0) * (4*y2 - 2*y1 + y0) // let e = w(inf) = x2 * y2 as t -> inf // x0 + x2, avoiding temporaries let p = &x0 + &x2; // y0 + y2, avoiding temporaries let q = &y0 + &y2; // x2 - x1 + x0, avoiding temporaries let p2 = &p - &x1; // y2 - y1 + y0, avoiding temporaries let q2 = &q - &y1; // w(0) let r0 = &x0 * &y0; // w(inf) let r4 = &x2 * &y2; // w(1) let r1 = (p + x1) * (q + y1); // w(-1) let r2 = &p2 * &q2; // w(-2) let r3 = ((p2 + x2) * 2 - x0) * ((q2 + y2) * 2 - y0); // Evaluating these points gives us the following system of linear equations. // // 0 0 0 0 1 | a // 1 1 1 1 1 | b // 1 -1 1 -1 1 | c // 16 -8 4 -2 1 | d // 1 0 0 0 0 | e // // The solved equation (after gaussian elimination or similar) // in terms of its coefficients: // // w0 = w(0) // w1 = w(0)/2 + w(1)/3 - w(-1) + w(2)/6 - 2*w(inf) // w2 = -w(0) + w(1)/2 + w(-1)/2 - w(inf) // w3 = -w(0)/2 + w(1)/6 + w(-1)/2 - w(1)/6 // w4 = w(inf) // // This particular sequence is given by Bodrato and is an interpolation // of the above equations. let mut comp3: BigInt = (r3 - &r1) / 3; let mut comp1: BigInt = (r1 - &r2) / 2; let mut comp2: BigInt = r2 - &r0; comp3 = (&comp2 - comp3) / 2 + &r4 * 2; comp2 = comp2 + &comp1 - &r4; comp1 = comp1 - &comp3; // Recomposition. The coefficients of the polynomial are now known. // // Evaluate at w(t) where t is our given base to get the result. add2(acc, r0.digits()); add2(acc, (comp1 << (BITS * 1 * i)).digits()); add2(acc, (comp2 << (BITS * 2 * i)).digits()); add2(acc, (comp3 << (BITS * 3 * i)).digits()); add2(acc, (r4 << (BITS * 4 * i)).digits()); } #[cfg(test)] mod tests { use super::*; #[cfg(feature = "u64_digit")] #[test] fn test_mac3_regression() { let b = [ 6871754923702299421, 18286959765922425554, 16443042141374662930, 11096489996546282133, 2264777838889483177, 504608311336467299, 9259121889498035011, 10723282102966246782, 14152556493169278620, 3003221725173785998, 12108300199485650674, 4411796769581982349, 1472853818082037140, 3839812824768537141, 566677271628895470, 17571088290177630367, 4074015775889626747, 16783683502945010460, 3672532206031614447, 13187923513085484119, 7867853909525328761, 12950070983027918062, 16468847655795609604, 16236260173878013911, 13584046646047390182, 3459823911019550977, 852221229786155372, 13320957730746441063, 15903144185056949084, 17968961288800765765, 3314535850615883964, 11164774408693138937, 296795981573878002, 13439622819313871747, 975505461732298298, 6320248106127902035, 1292261367530037116, 5457288991919109645, 9156327436088586665, 13214259773135401786, 11894959382522647196, 7347087210697207182, 10866433221888385981, 11517455022886216566, 16002875401603965132, 14910152116859046022, 13121658696980417474, 9896002308546761527, 2508026143263419489, 5630957157948330915, 14741609094906545841, 17816841519612664975, 7969630003685849408, 155645440736526982, 12636207152988003561, 11423906424129622745, 7683636929614516252, 18373475843711518761, 12517632064609218689, 9229683610001203481, 7466784812824133107, 669533494937267490, 5082436863236123102, 13002655060148900023, 13744987998466735055, 11291793723517314998, 13019038669516699882, 16709997141197914794, 5635685992939170942, 11675574645907803567, 4594226142456014804, 16573646927735932410, 1485870256663971571, 15846713039191416692, 6268579197046091479, 4148711486149996258, 12289594343226957541, 7248423051711675098, 11690743363052255577, 3624472201995805474, 8537222754743368136, 9139752523777531093, 10332892792833338770, 7037635035632196817, 4496405835920050629, 17391917705588355794, 14117717411488825371, 5230286663558119879, 17825506019213671261, 17404129971477111108, 11521727676625909194, 5238690179323183699, 5727780062420810465, 9632453973638740648, 337811100863346570, 13073228541428212927, 17709844765172234384, 13208921325370991444, 5431840578699639395, 17077925307816799261, 7209340156697508529, 12028994618496870845, 2544500160865141031, 11649654461126310578, 9365483541048471688, 14612538420978379687, 9873239918327058306, 1157472058577394095, 12375928197270581863, 11259024417929344257, 3285662610711925103, 1050951962862248344, 13573242938330525645, 6481773409427626042, 16024681689552681567, 2220783933082287757, 8929560899664301451, 64015232882626853, 11408281661939521111, 878781900624570608, 9905479987547252164, 5731582277472653511, 17783362590834199727, 13132721837581513886, 11245310560513633279, 7644137013939043642, 13922828459616614595, 448705611699584512, 11371313753562743476, 1574633155961622201, 2301463292785650126, 741402366344950323, 14185352113401593236, 9211130877800459742, 11565822612758649320, 14182824194529562358, 4341494334831461293, 15108767488023246095, 4205441133931479958, 17825783968798375241, 5574097067573038154, 16531064653177298756, 17267304977208102577, 928672208065810133, 8205510594424616558, 12543833966918246257, 86136389231850233, 16025485094311428670, 5207828176013117610, 13359327193114550712, 2794955638345677576, 3993304349404239314, 4994255720172128836, 7135313309521261953, 3325716756157017100, 4584134963117073140, 88101658911197316, 3369567695997157158, 6461054377325416109, 17386668567122758604, 3597625436035211312, 18145298865089787176, 11816690578299880852, 7452950893647760052, 1177645126198066735, 10342535382097449475, 598208441320935865, 12921535255416124667, 13109196922707708559, 8670507722665163833, 17373614756345962119, 3224893480553906007, 14808009166588879477, 14704014108115963684, 1462864287248162745, 4880369798466033386, 6588737531985967098, 7946857775405689623, 12748319198997944814, 9326770283997092048, 17003595393489642565, 17484594608149336453, 4190950067408592109, 17824678462034741067, 15702236130638266509, 5273424187690232454, 12023318566452513739, 7102078857285715052, 4369802176505332167, 10699689773538544377, 730467711008420891, 10262119215370320651, 6690738779737159913, 10562916257987913949, 14972385366243262684, 17611612385937387126, 14205605578073512987, 8713489693924424056, 16616344708337664878, 16742234424573023464, 2902884815897074359, 9156119555166935389, 9080622094288708744, 3581449124220285742, 15398432395479402853, 6362303494565643898, 15212154657001712988, 18252754350443257897, 12244862614504808605, 8814921661269777610, 5889164750855440803, 13877154483979742237, 1975853494990494526, 1453591120623605828, 1561842305134808950, 4104017706432470283, 18374510210661965759, 9803038902053058582, 15551403297159148863, 16533913772549484823, 14544914922020348073, 10919410908966885633, 17470299067773730732, 11601114871272073512, 14664333496960392615, 13186665624854933887, 14081619270477403715, 4675338296408349354, 13005625866084099819, 9826340006565688690, 8509069870313784383, 11413525526571910399, 6807684484531234716, 4618621816574516038, 4883039215446200876, 5183393926532623768, 10445125790248504163, 8703300688450317851, 1810657058322023328, 13343323798867891831, 1114348861126534128, 13117683625674818191, 6927011828473571783, 3034582737565944267, 4121820627922246500, 2068319599019676600, 4767868471095960483, 2803257298179131000, 9209930851438801799, 18163819238931070567, 13128522207164653478, 18335828098113199965, 8486377462588951609, 3277957111907517760, 2754092360099151521, 8933647340064032887, 11308566144424423461, 8932492907767510893, 17676321536634614180, 10916845309604942594, 1541736640790756953, 6693084648846615663, 2461388895988176852, 18262736604025878520, 15216140684185826151, 3888640441711583463, 14630778656568111440, 3821930990083597884, 6592159409049154819, 5773800580147691268, 14025025753393817356, 1143462425860692308, 7310246890521674728, 12759899287196682624, 17074850912425975309, 13639540485239781443, 11594492571041609459, 8086375866615071654, 2458700273224987435, 14188836372085884816, 14151374325605794048, 12856075220046811900, 17507597135374598747, 12763964479839179724, 3365341110795400221, 13808931773428143133, 17033299610882243549, 18227238137056935396, 14979713927050719147, 4275831394949546984, 8603067650574742183, 15568230725728908493, 2983251846901576618, 4855005009090541140, 8978290455364410739, 7585912958100257345, 7889636089238169609, 6157281389499351077, 16013269622819602387, 9224246297875214668, 4138161347252674082, 10318658241432357882, 9402564329926365826, 17394083647841321487, 4542513014713923099, 8667322649378182890, 576180375143955900, 18021784748061793599, 13203834948982480414, 13904284351856275257, 4244818956425434151, 1076055980570550161, 2674096971027047948, 104304434704934006, 2062855556986682483, 5786781659542854036, 6853220200637113363, 9593939255297136609, 1066166708380361418, 14725348327737457961, 16150748104690835108, 17931164130540362944, 18218341517410521707, 6187428325833810419, 9690875880801108718, 5756353469528306968, 2503319654515164798, 13274927231487272946, 10638128257539555489, 5896639022976119702, 15161011556181302784, 2677346843481863572, 604789272653420187, 13360196803831848409, 10012996491423918567, 5044454426037856014, 10524057648033789107, 5649671761089989854, 7387534256772100838, 8924072651833780120, 3785979389901456766, 2050691721810266829, 15376099431140621558, 17511662813348858473, 12, ]; let c = [ 13147625290258353449, 13817956093586917764, 18028234882233861888, 4293751923287888052, 14564141039952372119, 2676734207017121597, 6459642599270298327, 10514787163962869530, 3464485178085199795, 11257474764035059331, 12181451147060151288, 7771786629160476887, 5728497381328758601, 5895875676429179638, 16679607158645743277, 10404047442430847790, 16582081384308902247, 12490779806977231913, 11404651769234278221, 17022469412583392578, 16439338230633175949, 1063962396022446422, 4870572923632948252, 10243077795083132155, 17682233381781162062, 3717510388192897304, 10472572278890160024, 4405755291195612194, 17627642736326682742, 15119177646289231784, 14667151155773252610, 1618000287928404571, 13586901368491466481, 9480801770542358210, 11591874296843194205, 8397058357928253365, 578589728443805743, 1598611175229035508, 17769761727743406958, 8701373647057001365, 3491199179963360183, 14734752687818620066, 5882881716069715431, 17867956461647398152, 14317425986826618884, 3190976033715157155, 16025482572482863452, 198303002951605721, 13239788634860069155, 9176490930959914357, 13789370614942093263, 8719316129258342716, 8953451100830410047, 5127100131850962987, 5042215589496218651, 12195935831432585004, 16271477124635191788, 17042607302458382021, 6909951113544811251, 15867944577589614763, 12869536415455501541, 13449373980179917814, 5429607781375702916, 14690315137615067697, 6423399543123234984, 15319364673671319937, 5766347079728187383, 9497305192864606751, 2186351927817601391, 10726914960258697501, 6088420666246691919, 1588440693016474445, 2604959928768677511, 17616186617681342252, 10535006669694135493, 13489006267185033075, 15502143361666125994, 16502406772857573234, 10575734691312906463, 10716474667815258981, 9710545289905473439, 3854962820702807947, 5378807396667958578, 12445857039679749013, 3960937645922969357, 9829760523341564006, 9212167324275861816, 11422368668113634154, 10684460016299893830, 11389419764702616711, 3899200183251946009, 2093729712958211017, 8420392268215053797, 6398774523536552388, 10852749009148352925, 5289144597498232565, 17703908865205386695, 6907742189144573057, 1784946329061543285, 15480049270321874965, 12069121519676878616, 17812799898774546955, 11948193027013007431, 3884323573006797139, 6847241152178866159, 12199935709218616587, 3955204591920032162, 14878266626017125196, 7278030477420395848, 10161863746736807272, 9207356190672684457, 4601854808843007498, 6775986836344704023, 17288427592206154151, 484532203475900068, 18118416415768866724, 6355480490988086744, 3208810669246831205, 13957974139288542819, 8396394607132645103, 15228026780031354119, 14498855337604982920, 14141161076130564520, 6588603191636571246, 3999628253355964982, 575393068537655797, 5657615255395137815, 5633326538404084103, 12326562882758080143, 3543480102419886151, 6824968844300019651, 3267458303116092202, 6237792365531735545, 7469544494204334597, 15133093961814251253, 6772265097243462865, 5750218230297679586, 15133043154817660619, 13838897645290708193, 1698455434074605058, 1416851634747812455, 1433730608162832030, 4396199899836953731, 11478281064341415007, 1199305835874995069, 12461220549480843598, 3786960620800323764, 1359737533861421574, 5683800489224722555, 580114063914071460, 3757480794795278521, 13350893050786101167, 5864294767515313613, 13667186506174093283, 10644721863115106069, 4089596839694426493, 837360057072705787, 14661298745941209853, 3135603497841243154, 8588389252943247567, 3180539906709497729, 9920619693463058306, 4532986872992016572, 16671485218531724914, 16237535739330707258, 3392767051844917712, 6253243888910507007, 6138565275365265434, 10788645409322247025, 2998545083522261349, 4393635535422254464, 162283948928616560, 6581058835892498610, 9044842225211179928, 3359587585025090294, 4774711746392882472, 12671200872687548503, 5910134937871058397, 5003751340241222878, 4967360099981268641, 8911591385760571590, 8159270265734967930, 5250229866305601451, 9551428753943119262, 8689322272982432960, 10836071047039045386, 17213966296648357737, 9670979912487313863, 8149443095351359584, 5882663205147794724, 1077285439953280724, 9538056828068584607, 6534627272003475907, 4182635403810470796, 4332023173746385204, 18043427676849450827, 1544903479164552030, 12808718740097386201, 4743835518042863198, 17533308810746778943, 2436162195122352530, 13717567738827779707, 16498190890660698054, 8446479819925879748, 13026080039828457667, 10242288816864319380, 16805676933455246691, 8854224454209663170, 12881936897446363181, 14318173900990076031, 17263412233699302472, 1175398600063038674, 12303198178060136245, 5262693362410688618, 2449023658743880786, 7851992903947432349, 15279972405631504407, 12782492794198106006, 454161448971247291, 7208428618685987862, 2808315703288943474, 15547213201445152112, 4195163971319471362, 5077844356227078783, 6228496807545876867, 8018540845186766480, 12802276286029182659, 17873658985235511282, 405964923119895900, 17005602789111483415, 15323511615180015542, 3777673967701314271, 11241595450806936514, 18094205811239804553, 4945226306748157777, 13126826405187610008, 18401109742831785725, 12038829763881934869, 6883152103015744232, 6888604044125585130, 10327133149324643136, 9786783078753767897, 7728244798165310883, 13992043126602427065, 12760431374402895816, 10556094269445313552, 370205722038466820, 2237385387127770787, 3008501418666326571, 2147796682874314438, 11177403945853274771, 394056223101551114, 17534487287334816941, 881808126732102067, 4246224751203270716, 6113128358498682501, 1188932545968905738, 12765644408650990762, 8081000787691948556, 648553016175951475, 13679613339055618508, 13341452083201419987, 16710796306331641196, 14950547258962926774, 5807411999567421647, 51486220608905397, 11495154677696979138, 9566551468999057159, 9404650285252518485, 15936039807347909292, 9926926746640651811, 8137529358194870999, 8409600195382297763, 7353893979385221928, 13160302875690198406, 348690545671757035, 9037218723869788888, 17926585726505969574, 10803900675631258757, 6393072209298283246, 16096417936354328220, 9646360537089934694, 13770356122351384928, 16836674286434938459, 7541946872500761286, 9048263944605955661, 16780366954521256652, 7343863344205297175, 12789916470639650059, 5777346297355673119, 3199552193495347726, 12230742086629356177, 7003231206534047938, 15090957803858528744, 17037481317622823117, 3297597585907869563, 2697945267713108093, 4292423210234323248, 3611346819357503037, 7143735793987221927, 7192307513286386565, 17787283681233014873, 12357966577423097448, 8897136197269501397, 11902132993155439534, 3134549357805042842, 13190859350132812532, 2953055179222338302, 14072479035614746298, 623716608321502842, 13012840714155111804, 9113471173003784658, 3832090523063788219, 11686697139180356613, 9220715948534448005, 10475815552871271805, 13316455608734752259, 3256936992714735238, 11886029809711683060, 1154889652278063077, 2634050492458919284, 15799574960065328453, 4854385868907776158, 4308561300452445774, 18158501743185507870, 494961281052444285, 13230103283989646999, 4290343182499439317, 2897833401622123527, 1828737779143272347, 10192978009672844498, 10197386440201448306, 16716143215455134742, 15610114368473665198, 6236681643047286973, 12762824210749799030, 10807635853279558353, 11353446277082394704, 7511532745578783402, 7171399474829708082, 2443271458861652456, 18046286184730984000, 1631291998347686895, 5333915858453483562, 4279428177587669193, 4079835446959802508, 14290782115827722683, 6259655031577342838, 14581460384506564304, 235151974716865360, 2375317628907755058, 12458887693759984881, 2860995391934282660, 17774376172142139929, 17358804008079603231, 2216198936056406536, 2563098348647162202, 774854408223515953, 12219835071659426404, 2185427726156502437, 8977240783566213019, 10950053189740163780, 15333460456641375067, 15414859166425218506, 16627722666231706432, 14933789823667915188, 7893509177447272752, 5576840844608359783, 9639046067346127903, 6034870669926683205, 11074229566077202561, 7734172323678793750, 1797022077506253706, 4175135546481691973, 4576531916446872861, 11073018132808499885, 9004329344974888991, 2579957018554908013, 16723993098086799559, 8849326108645639933, 1190731350374367414, 15196122081549855262, 16510124270150231915, 1447369806052266158, 1774117429703831561, 3272947319047150592, 6086749417328134594, 114186026684487132, 15881404973090653236, 9002767864228350415, 8632935895349074342, 14189358814161984679, 7273121617103693424, 3720897725211288407, 17385088912598509226, 17763377168623207811, 3011652710253791434, 13026181299902362083, 7673465031457219376, 8976686724731444924, 1602632530339248239, 7322563236300692731, 17611256894860100558, 6585524259854016494, 13024412741537787009, 6490348356225390820, 10475028766694832415, 4171072186129163678, 8067851189059922503, 13321938328018146758, 2388045447565404129, 12628485341454603822, 10515272459175323665, 5141134415272454070, 15533371382800133770, 5089921040728608575, 9922174346147797518, 2286765044618595826, 458550603008652679, 1895551360015713043, 17608310488293104847, 3041900727372287447, 14788640656316180904, 8006597265367839623, 6172940096066506343, 5001938689099706064, 11456390799634570508, 58114059478872995, 13813208350157959983, 7192129467061995988, 15458065357391712248, 1184709156376072909, 4997369113101583984, 11962098224621896302, 15957925570647432972, 9768648025404723859, 16066042591100391809, 14826843103086137650, 15530089295707983043, 14757548535314259278, 12272651610971114578, 11815510217344882354, 7863174743199280885, 17755545598189623361, 3623688651342862124, 846900727574364473, 4058087733004472364, 9766249185594229219, 8203083537227057882, 2514240782116496856, 13013220914916706232, 7479093476304703557, 13599783865226501576, 15101635775647230555, 7679618582697439061, 3809012502593902516, 17181248094867317535, 9184314850829556852, 17135643679321121988, 16551911434983848191, 16563989164660839146, 5244550954203347299, 7468243134930758384, 13848792956096067953, 299147213373350316, 4234339785402518959, 8316379046881991503, 15054498767105089317, 15245345469072520312, 169003686610660574, 8905168983426000291, 14079614647232314662, 10677487605853621326, 486644500614977963, 4315204642211280928, 13378617481135356106, 17475120936205263193, 7054688890001081620, 4890150051524335365, 16929286679364707850, 12404641144465776093, 85729750914301011, 7518958607192096844, 12335244912121726376, 441058371959341821, 15283845211776523277, 11365329781782022447, 7176368314974115909, 13402576699022366440, 9612930864140895738, 1551492131293754732, 15625022379217650131, 16853815349026997223, 10176564334158763844, 11561712818786302756, 10721760754726884570, 16211944886847212142, 6455169008048578331, 16442277863996881453, 11966295676197364531, 17131994341597087852, 10178415200084263095, 17241579229376875844, 16595331811574273072, 15514521091896721175, 10273857151649071793, 16902595879470117012, 17044001876395421463, 6241464946584582238, 6948336526969806585, 618342450528567894, 11266394538973042131, 13911827545633749019, 5770757761516661921, 4237426824475464361, 6137903415464019236, 16948218557528241218, 13342541955783637763, 12228044034020334487, 3753346696590480376, 12798240801313956988, 16337512518975517925, 17029293450980009677, 17889170535515757468, 14215875855934760379, 6048723980155309955, 7751681766991188778, 9324053942011976933, 6806752775473648551, 16491946688185935526, 17973734037621739928, 16521618754491099078, 15814146101747955693, 17072736172673770992, 560386638362049457, 9315742694497383404, 14003511454248083195, 505571467191783211, 15321198489161153019, 67644988835003625, 422740534693308350, 1588696840338933253, 17633924999495432514, 3578955538397900717, 4350434105925504139, 17520065248429114920, 15948482628426996406, 16339123994002177423, 14962340825416078820, 16377030826129395507, 3728945733790793859, 14040902081706983834, 6245445984351877668, 15109200712778355913, 6876007592769255303, 2817332194593868297, 14642462812181536002, 13241495844336600578, 17508429190834543309, 9979949640512203943, 11024829646351554638, 16593085213286597946, 3786341713932228381, 4854315828914728926, 4226218666904293494, 8427728822561673998, 7350284610946156715, 15819368048130139112, 8256096529517474967, 3164838434037013186, 7181083254407808229, 14392138511139873518, 17742848920305479369, 14254286401886846925, 13172848038012405804, 203991661409228704, 12155338881267997435, 15596778231824136139, 4270398294351523748, 841800590896491878, 1324356347939565174, 1635131684701069722, 9402955035355081296, 1217032459175096228, 814223664322441499, 15135019617633870019, 12555639443566847383, 11065144808269184833, 1793647298364803083, 744335551991850623, 8586945353992422223, 13891984397850330431, 13168278299568698045, 2545505069878626309, 2345784529656940996, 11238050768519698690, 145002862188778047, 14056901992927566251, 7146776997541924640, 11964908621390755985, 3287082359454318848, 7997294085866872179, 5423940255508089295, 4669857898097690050, 11333522019809124025, 7524197645486269287, 17976672080799403364, 9172262822040915360, 158857927726516306, 7825225378554946108, 9418576621795701508, 7633907046040364747, 18268626574958706065, 3209003992606419777, 16433724431228669029, 11533879023784257295, 7352494819227083416, 9550528667280588513, 17649577381405647635, 3464121828599745965, 10524312096092076686, 16298229441805025435, 12299501175855694268, 5234483534956328223, 6842998262033517680, 3405412371253551971, 12961834222487484113, 8329667703663634728, 10113768572787795201, 437973618905269097, 10518227023647484735, 15505971298645719880, 16080360285628075895, 3253079608258240664, 9442135189206070131, 2620029667482460392, 13058843258931508372, 13398588232276089878, 2013946258885953106, 2777554235294156890, 7727335788600791403, 64926713702036664, 7017058603665827477, 3038023548514697220, 1884676627569135536, 11691207067273431143, 10072076283563998720, 13307639350090691756, 16097417013067765232, 1046820113070464713, 686419524967082232, 16868023154965697840, 9866592207237669169, 434426218272207007, 15594721674408845443, 4951793482938178894, 5328839429244804401, 6948444829657740645, 1250147824386974181, 3550991145492617480, 6903375020760383265, 5556228127567021487, 13761117792143803710, 15185125920584997092, 8186466630413736182, 4802907899488331586, 15305034246197656170, 15396976225074357341, 5898890255224717338, 3615484144772658086, 18255788598509486615, 224652660554020763, 13466057775273969203, 2077408507156283322, 2342023270473665603, 8947077544711176259, 5306736138640896482, 4480826977335219320, 3788577265714804046, 115308722462922151, 7375990846913556901, 11736854490599587323, 5076771704562414238, 15553536672697466685, 18090905433616951399, 4188493781910494747, 15181059585004440209, 12728148632534416192, 6722182881759806025, 13780369372289967994, 3732668177228110489, 3787487561117269614, 5162113090068803421, 4321209401054627716, 5448669100032977354, 18291843216134979053, 16776289611211531598, 1885119013176564798, 9819767057810457229, 9641605351052741528, 15675183391486745167, 7616169275030402931, 15993936796479971901, 9454285932998973051, 17536483736707322645, 13392933552816987057, 8637439302534754550, 540899472066855809, 16629709388332749089, 13733105412819355808, 14746175220939553318, 2846952298407666021, 2891977601791383828, 5696908477729602226, 11016605210700034776, 16941067307488182843, 6211355506521287507, 16542299272345996744, 3303613293413685324, 1629768918920532660, 4206151598734336232, 8856046512946232478, 4907901964445375077, 14400940791045719898, 6525037265010054850, 2845928272349757088, 15487802580883373670, 9169720274701972562, 5985973322812415499, 13260753279459456665, 17130834352417810395, 10504159994735949472, 3619665201800936886, 6177405351801242874, 17314717210185132120, 10635416390598362752, 3965067791232986010, 4137222868235076149, 7349861099139148757, 13855902416442714188, 3758295764877447132, 2127539446373659348, 7398648921373235157, 10530977609779069122, 2057082983915369887, 15095469010920249805, 1580580744862861737, 1385280835524895944, 3735648750536184988, 13975651103105108932, 12560143273028504000, 213932257778062629, 14025207273678863547, 1676558185650908917, 3681689509396718388, 3722143195009944583, 6372328340754588443, 10661271971253598404, 12865667632468835094, 16100956261366638373, 11045168180887164035, 5967989014180680940, 15635382253084283895, 10672630067495824386, 3671716856885117446, 10087953011045522378, 12966649859522423914, 7760990551799493049, 6773507642155574420, 14320444088036226729, 996203594183873620, 6192894784937493039, 4156453068089966167, 14572012258150145006, 12694436615363442069, 9393452532594598725, 7073980584197012440, 3092044667654940896, 13855475386227226214, 4309098798809069243, 17846796523885690871, 13567621519152235542, 15083768013978066571, 4928428566683275123, 6358144983716124065, 5815136002584686049, 8730978481571655079, 7899439375250672635, 14524588032253020995, 9810453005255777832, 4283615174004546182, 4910404083022612904, 5889820858976629278, 16526481241932287977, 9532234053410906113, 12393033057707332749, 12925587840306057080, 10366100576119055483, 6171980884320519881, 6370785275483681135, 8381526621841046029, 5551091520919536756, 12950765990114654837, 6451545362694246818, 212258237904426316, 17609333615515129459, 16595363338989541409, 17025961636346735400, 10271948129080248406, 10944228647786476233, 5467386369086945871, 1304225602762032822, 16166120916726245386, 9432487283289925931, 3403761315752290587, 3141021554091328928, 10971462138407674348, 10105449417179637906, 3942240849395932405, 10366411633985305351, 659554731028325691, 17091333474944352463, 612319979868231629, 17382969496671106101, 3825928121744631575, 6919629698697448941, 3047982536888198540, 8582263155177383434, 10489954932217807453, 18043360586501370656, 16839643971175241779, 3859513000284354780, 10803271797516731820, 8797248475477069569, 4834788502968724109, 10636072941935319265, 15738621943484162587, 3646521574321304278, 16944083908124496190, 16148256726139579321, 1609665271498664710, 1362054633058989594, 13973388908791057772, 6345006526009146382, 2518534936752010021, 659541823645224189, 10968167928774784973, 7543306179097411926, 9456023891569360398, 5349741969482277027, 8323748029139171407, 11280182066584422642, 3780197930314489144, 11850380628777309039, 9657986102535984497, 5218157717868740572, 7171503646973777516, 5852967071087962442, 17762051133445851451, 13539879275779472444, 10231713150096078048, 13415553313620113202, 12765372888710309095, 15057130630522842392, 14677710651300800748, 10692853438748252520, 12459043459128327446, 2895873908250910074, 12414654299833871003, 13971031683534816634, 13847640779080634026, 217295692307502497, 7750768797035502178, 290949611993301720, 10199100136702866567, 15495972441839001396, 13198452434198427151, 2440498893626898052, 15118747988064647069, 6537279940542355961, 8712445311047767491, 17256665922722282910, 13175508019793567143, 10218901675074990248, 13394299990216654516, 5977932445410319532, 5913587457706598533, 18017099150205847183, 10803505436178917593, 15504988698835663005, 11647690777417283778, 13263578958104628128, 6887980138658259663, 12615506930751501449, 4362286963260481429, 17936849618704425417, 8369687071549056310, 6873677162393948122, 8962347665252911678, 6575009038253218272, 17049757839609406426, 18000487384002665628, 17743261078931639159, 7069552289073828088, 2053907584370525129, 6092754463992814730, 7835970278896264421, 8747049071648962742, 9020604727379960828, 9632547032149786788, 16485371852605585328, 589786022609761499, 14198172759212036212, 3179321442557148353, 9275833134889979290, 4203798446932368841, 1997647913473930975, 2518811456650703083, 7750350188524367372, 8204413870688842329, 4683962365740774568, 1038502292158797902, 416255872857165019, 89452159243564340, 5029544632341923837, 9006839419087725471, 6081309378730152882, 6841819644499887187, 1989550502574820483, 13603604083811099797, 17579259537599657917, 3688889816642246075, 8365081349347412069, 9781470991802711607, 5096192245902990289, 1498837910524874201, 8053001241713783407, 13235502474453488717, 14236495286020360865, 1736617016599872719, 6171162219819586226, 10365771078075021733, 7005440335994057913, 15987156790865471266, 6743350458772878812, 13939320505807395210, 18411835973679513875, 14557893705645834250, 11183480228569397732, 2863370600396906941, 3249734688507432577, 10075558144505269497, 2962113710307186842, 14006648851316589492, 7556865444223108417, 16635752120601038989, 2805784706247063393, 1921256089647591677, 10043101807995880550, 17183135665189377543, 15209331403547677849, 9759674000009984076, 6188634504854345563, 17429444123311113173, 12716643325990854245, 4404673046468281426, 14977242545159900045, 2353738321397058672, 2217587216444012952, 17848724221428205646, 7788107721465269627, 4209425388750317735, 15986838006612180795, 10448760854792387460, 2181718159289817159, 10626737123343057134, 8531679111527745250, 2221563690578844859, 7279790679521017728, 10678979618998152285, 17119267278437855914, 14741366633087203734, 13977821575914403172, 13984542610460459828, 17859323614174580751, 8221319720268548319, 7448166339196439012, 9427945230078429775, 15205875846647517591, 16806327021489489097, 3923284971739738878, 8300291583515256892, 5684696181844315010, 4112709175543117372, 1305238720762, ]; let a1 = &mut [0; 1341]; let a2 = &mut [0; 1341]; let a3 = &mut [0; 1341]; //print!("{} {}", b.len(), c.len()); long(a1, &b, &c); karatsuba(a2, &b, &c); assert_eq!(&a1[..], &a2[..]); // println!("res: {:?}", &a1); toom3(a3, &b, &c); assert_eq!(&a1[..], &a3[..]); } } num-bigint-dig-0.8.2/src/algorithms/mod.rs000064400000000000000000000006701046102023000165350ustar 00000000000000#![allow(clippy::many_single_char_names)] mod add; mod bits; mod cmp; mod div; mod gcd; mod jacobi; mod mac; mod mod_inverse; mod mul; mod shl; mod shr; mod sub; pub use self::add::*; pub use self::bits::*; pub use self::cmp::*; pub use self::div::*; pub use self::gcd::*; pub use self::jacobi::*; pub use self::mac::*; pub use self::mod_inverse::*; pub use self::mul::*; pub use self::shl::*; pub use self::shr::*; pub use self::sub::*; num-bigint-dig-0.8.2/src/algorithms/mod_inverse.rs000064400000000000000000000060731046102023000202730ustar 00000000000000use alloc::borrow::Cow; use num_traits::{One, Signed}; use crate::algorithms::extended_gcd; use crate::{BigInt, BigUint}; /// Calculate the modular inverse of `g`. /// Implementation is based on the naive version from wikipedia. #[inline] pub fn mod_inverse(g: Cow, n: Cow) -> Option { let (d, x, _) = extended_gcd(g, n.clone(), true); if !d.is_one() { return None; } let x = x.unwrap(); if x.is_negative() { Some(x + n.as_ref()) } else { Some(x) } } #[cfg(test)] mod tests { use super::*; use crate::integer::Integer; use num_traits::FromPrimitive; use crate::traits::ModInverse; #[test] fn test_mod_inverse() { let tests = [ ["1234567", "458948883992"], ["239487239847", "2410312426921032588552076022197566074856950548502459942654116941958108831682612228890093858261341614673227141477904012196503648957050582631942730706805009223062734745341073406696246014589361659774041027169249453200378729434170325843778659198143763193776859869524088940195577346119843545301547043747207749969763750084308926339295559968882457872412993810129130294592999947926365264059284647209730384947211681434464714438488520940127459844288859336526896320919633919"], ["-10", "13"], ["-6193420858199668535", "2881"], ]; for test in &tests { let element = BigInt::parse_bytes(test[0].as_bytes(), 10).unwrap(); let modulus = BigInt::parse_bytes(test[1].as_bytes(), 10).unwrap(); //println!("{} modinv {}", element, modulus); let inverse = element.clone().mod_inverse(&modulus).unwrap(); //println!("inverse: {}", &inverse); let cmp = (inverse * &element).mod_floor(&modulus); assert_eq!( cmp, BigInt::one(), "mod_inverse({}, {}) * {} % {} = {}, not 1", &element, &modulus, &element, &modulus, &cmp ); } // exhaustive tests for small numbers for n in 2..100 { let modulus = BigInt::from_u64(n).unwrap(); for x in 1..n { for sign in vec![1i64, -1i64] { let element = BigInt::from_i64(sign * x as i64).unwrap(); let gcd = element.gcd(&modulus); if !gcd.is_one() { continue; } let inverse = element.clone().mod_inverse(&modulus).unwrap(); let cmp = (&inverse * &element).mod_floor(&modulus); //println!("inverse: {}", &inverse); assert_eq!( cmp, BigInt::one(), "mod_inverse({}, {}) * {} % {} = {}, not 1", &element, &modulus, &element, &modulus, &cmp ); } } } } } num-bigint-dig-0.8.2/src/algorithms/mul.rs000064400000000000000000000013461046102023000165540ustar 00000000000000use crate::algorithms::mac3; use crate::big_digit::{BigDigit, DoubleBigDigit, BITS}; use crate::BigUint; #[inline] pub fn mul_with_carry(a: BigDigit, b: BigDigit, acc: &mut DoubleBigDigit) -> BigDigit { *acc += (a as DoubleBigDigit) * (b as DoubleBigDigit); let lo = *acc as BigDigit; *acc >>= BITS; lo } pub fn mul3(x: &[BigDigit], y: &[BigDigit]) -> BigUint { let len = x.len() + y.len() + 1; let mut prod = BigUint { data: smallvec![0; len], }; mac3(&mut prod.data[..], x, y); prod.normalized() } pub fn scalar_mul(a: &mut [BigDigit], b: BigDigit) -> BigDigit { let mut carry = 0; for a in a.iter_mut() { *a = mul_with_carry(*a, b, &mut carry); } carry as BigDigit } num-bigint-dig-0.8.2/src/algorithms/shl.rs000064400000000000000000000016251046102023000165450ustar 00000000000000use alloc::borrow::Cow; use core::iter::repeat; use smallvec::SmallVec; use crate::big_digit::BITS; use crate::BigUint; #[inline] pub fn biguint_shl(n: Cow, bits: usize) -> BigUint { let n_unit = bits / BITS; let mut data = match n_unit { 0 => n.into_owned().data, _ => { let len = n_unit + n.data.len() + 1; let mut data = SmallVec::with_capacity(len); data.extend(repeat(0).take(n_unit)); data.extend(n.data.iter().cloned()); data } }; let n_bits = bits % BITS; if n_bits > 0 { let mut carry = 0; for elem in data[n_unit..].iter_mut() { let new_carry = *elem >> (BITS - n_bits); *elem = (*elem << n_bits) | carry; carry = new_carry; } if carry != 0 { data.push(carry); } } BigUint::new_native(data) } num-bigint-dig-0.8.2/src/algorithms/shr.rs000064400000000000000000000014421046102023000165500ustar 00000000000000use alloc::borrow::Cow; use num_traits::Zero; use smallvec::SmallVec; use crate::big_digit::{BigDigit, BITS}; use crate::BigUint; use crate::VEC_SIZE; #[inline] pub fn biguint_shr(n: Cow, bits: usize) -> BigUint { let n_unit = bits / BITS; if n_unit >= n.data.len() { return Zero::zero(); } let mut data: SmallVec<[BigDigit; VEC_SIZE]> = match n { Cow::Borrowed(n) => n.data[n_unit..].into(), Cow::Owned(n) => n.data[n_unit..].into(), }; let n_bits = bits % BITS; if n_bits > 0 { let mut borrow = 0; for elem in data.iter_mut().rev() { let new_borrow = *elem << (BITS - n_bits); *elem = (*elem >> n_bits) | borrow; borrow = new_borrow; } } BigUint::new_native(data) } num-bigint-dig-0.8.2/src/algorithms/sub.rs000064400000000000000000000064271046102023000165550ustar 00000000000000use core::cmp; use core::cmp::Ordering::*; use num_traits::Zero; use smallvec::SmallVec; use crate::algorithms::cmp_slice; use crate::big_digit::{BigDigit, SignedDoubleBigDigit, BITS}; use crate::bigint::Sign::{self, *}; use crate::{BigUint, VEC_SIZE}; /// Subtract with borrow: #[inline] pub fn sbb(a: BigDigit, b: BigDigit, acc: &mut SignedDoubleBigDigit) -> BigDigit { *acc += a as SignedDoubleBigDigit; *acc -= b as SignedDoubleBigDigit; let lo = *acc as BigDigit; *acc >>= BITS; lo } pub fn sub2(a: &mut [BigDigit], b: &[BigDigit]) { let mut borrow = 0; let len = cmp::min(a.len(), b.len()); let (a_lo, a_hi) = a.split_at_mut(len); let (b_lo, b_hi) = b.split_at(len); for (a, b) in a_lo.iter_mut().zip(b_lo) { *a = sbb(*a, *b, &mut borrow); } if borrow != 0 { for a in a_hi { *a = sbb(*a, 0, &mut borrow); if borrow == 0 { break; } } } // note: we're _required_ to fail on underflow assert!( borrow == 0 && b_hi.iter().all(|x| *x == 0), "Cannot subtract b from a because b is larger than a." ); } // Only for the Sub impl. `a` and `b` must have same length. #[inline] pub fn __sub2rev(a: &[BigDigit], b: &mut [BigDigit]) -> BigDigit { debug_assert!(b.len() == a.len()); let mut borrow = 0; for (ai, bi) in a.iter().zip(b) { *bi = sbb(*ai, *bi, &mut borrow); } borrow as BigDigit } pub fn sub2rev(a: &[BigDigit], b: &mut [BigDigit]) { debug_assert!(b.len() >= a.len()); let len = cmp::min(a.len(), b.len()); let (a_lo, a_hi) = a.split_at(len); let (b_lo, b_hi) = b.split_at_mut(len); let borrow = __sub2rev(a_lo, b_lo); assert!(a_hi.is_empty()); // note: we're _required_ to fail on underflow assert!( borrow == 0 && b_hi.iter().all(|x| *x == 0), "Cannot subtract b from a because b is larger than a." ); } pub fn sub_sign(a: &[BigDigit], b: &[BigDigit]) -> (Sign, BigUint) { // Normalize: let a = &a[..a.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)]; let b = &b[..b.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)]; match cmp_slice(a, b) { Greater => { let mut a: SmallVec<[BigDigit; VEC_SIZE]> = a.into(); sub2(&mut a, b); (Plus, BigUint::new_native(a)) } Less => { let mut b: SmallVec<[BigDigit; VEC_SIZE]> = b.into(); sub2(&mut b, a); (Minus, BigUint::new_native(b)) } _ => (NoSign, Zero::zero()), } } #[cfg(test)] mod tests { use super::*; use num_traits::Num; use crate::BigInt; #[test] fn test_sub_sign() { fn sub_sign_i(a: &[BigDigit], b: &[BigDigit]) -> BigInt { let (sign, val) = sub_sign(a, b); BigInt::from_biguint(sign, val) } let a = BigUint::from_str_radix("265252859812191058636308480000000", 10).unwrap(); let b = BigUint::from_str_radix("26525285981219105863630848000000", 10).unwrap(); let a_i = BigInt::from_biguint(Plus, a.clone()); let b_i = BigInt::from_biguint(Plus, b.clone()); assert_eq!(sub_sign_i(&a.data[..], &b.data[..]), &a_i - &b_i); assert_eq!(sub_sign_i(&b.data[..], &a.data[..]), &b_i - &a_i); } } num-bigint-dig-0.8.2/src/bigint.rs000064400000000000000000002574771046102023000151040ustar 00000000000000#![allow(clippy::suspicious_arithmetic_impl)] #[allow(deprecated, unused_imports)] use alloc::borrow::Cow; use alloc::string::String; use alloc::vec::Vec; use core::cmp::Ordering::{self, Equal, Greater, Less}; use core::default::Default; use core::hash::{Hash, Hasher}; use core::iter::{Product, Sum}; use core::ops::{ Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign, Mul, MulAssign, Neg, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign, }; use core::str::{self, FromStr}; use core::{fmt, mem}; #[cfg(has_i128)] use core::{i128, u128}; use core::{i64, u64}; #[cfg(feature = "serde")] use serde; #[cfg(feature = "zeroize")] use zeroize::Zeroize; use crate::integer::{Integer, Roots}; use num_traits::{ CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, FromPrimitive, Num, One, Pow, Signed, ToPrimitive, Zero, }; use self::Sign::{Minus, NoSign, Plus}; use super::ParseBigIntError; use super::VEC_SIZE; use crate::big_digit::{self, BigDigit, DoubleBigDigit}; use crate::biguint; use crate::biguint::to_str_radix_reversed; use crate::biguint::{BigUint, IntDigits}; use smallvec::SmallVec; use crate::IsizePromotion; use crate::UsizePromotion; use crate::algorithms::{extended_gcd, mod_inverse}; use crate::biguint::IntoBigUint; use crate::traits::{ExtendedGcd, ModInverse}; /// A Sign is a `BigInt`'s composing element. #[derive(PartialEq, PartialOrd, Eq, Ord, Copy, Clone, Debug, Hash)] pub enum Sign { Minus, NoSign, Plus, } impl Default for Sign { fn default() -> Sign { Sign::NoSign } } #[cfg(feature = "zeroize")] impl zeroize::DefaultIsZeroes for Sign {} impl Neg for Sign { type Output = Sign; /// Negate Sign value. #[inline] fn neg(self) -> Sign { match self { Minus => Plus, NoSign => NoSign, Plus => Minus, } } } impl Mul for Sign { type Output = Sign; #[inline] fn mul(self, other: Sign) -> Sign { match (self, other) { (NoSign, _) | (_, NoSign) => NoSign, (Plus, Plus) | (Minus, Minus) => Plus, (Plus, Minus) | (Minus, Plus) => Minus, } } } #[cfg(feature = "serde")] impl serde::Serialize for Sign { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer, { // Note: do not change the serialization format, or it may break // forward and backward compatibility of serialized data! match *self { Sign::Minus => (-1i8).serialize(serializer), Sign::NoSign => 0i8.serialize(serializer), Sign::Plus => 1i8.serialize(serializer), } } } #[cfg(feature = "serde")] impl<'de> serde::Deserialize<'de> for Sign { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, { use serde::de::Error; use serde::de::Unexpected; let sign: i8 = serde::Deserialize::deserialize(deserializer)?; match sign { -1 => Ok(Sign::Minus), 0 => Ok(Sign::NoSign), 1 => Ok(Sign::Plus), _ => Err(D::Error::invalid_value( Unexpected::Signed(sign.into()), &"a sign of -1, 0, or 1", )), } } } /// A big signed integer type. #[derive(Clone, Debug)] pub struct BigInt { pub(crate) sign: Sign, pub(crate) data: BigUint, } /// Return the magnitude of a `BigInt`. /// /// This is in a private module, pseudo pub(crate) #[cfg(feature = "rand")] pub fn magnitude(i: &BigInt) -> &BigUint { &i.data } /// Return the owned magnitude of a `BigInt`. /// /// This is in a private module, pseudo pub(crate) #[cfg(feature = "rand")] pub fn into_magnitude(i: BigInt) -> BigUint { i.data } impl PartialEq for BigInt { #[inline] fn eq(&self, other: &BigInt) -> bool { self.cmp(other) == Equal } } impl Eq for BigInt {} impl Hash for BigInt { fn hash(&self, state: &mut H) { self.sign.hash(state); self.data.hash(state); } } impl PartialOrd for BigInt { #[inline] fn partial_cmp(&self, other: &BigInt) -> Option { Some(self.cmp(other)) } } impl Ord for BigInt { #[inline] fn cmp(&self, other: &BigInt) -> Ordering { let scmp = self.sign.cmp(&other.sign); if scmp != Equal { return scmp; } match self.sign { NoSign => Equal, Plus => self.data.cmp(&other.data), Minus => other.data.cmp(&self.data), } } } impl Default for BigInt { #[inline] fn default() -> BigInt { Zero::zero() } } #[cfg(feature = "zeroize")] impl Zeroize for BigInt { fn zeroize(&mut self) { self.sign.zeroize(); self.data.zeroize(); } } impl fmt::Display for BigInt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad_integral(!self.is_negative(), "", &self.data.to_str_radix(10)) } } impl fmt::Binary for BigInt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad_integral(!self.is_negative(), "0b", &self.data.to_str_radix(2)) } } impl fmt::Octal for BigInt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad_integral(!self.is_negative(), "0o", &self.data.to_str_radix(8)) } } impl fmt::LowerHex for BigInt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad_integral(!self.is_negative(), "0x", &self.data.to_str_radix(16)) } } impl fmt::UpperHex for BigInt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut s = self.data.to_str_radix(16); s.make_ascii_uppercase(); f.pad_integral(!self.is_negative(), "0x", &s) } } // Negation in two's complement. // acc must be initialized as 1 for least-significant digit. // // When negating, a carry (acc == 1) means that all the digits // considered to this point were zero. This means that if all the // digits of a negative BigInt have been considered, carry must be // zero as we cannot have negative zero. // // 01 -> ...f ff // ff -> ...f 01 // 01 00 -> ...f ff 00 // 01 01 -> ...f fe ff // 01 ff -> ...f fe 01 // ff 00 -> ...f 01 00 // ff 01 -> ...f 00 ff // ff ff -> ...f 00 01 #[inline] fn negate_carry(a: BigDigit, acc: &mut DoubleBigDigit) -> BigDigit { *acc += (!a) as DoubleBigDigit; let lo = *acc as BigDigit; *acc >>= big_digit::BITS; lo } // !-2 = !...f fe = ...0 01 = +1 // !-1 = !...f ff = ...0 00 = 0 // ! 0 = !...0 00 = ...f ff = -1 // !+1 = !...0 01 = ...f fe = -2 impl Not for BigInt { type Output = BigInt; fn not(mut self) -> BigInt { match self.sign { NoSign | Plus => { self.data += 1u32; self.sign = Minus; } Minus => { self.data -= 1u32; self.sign = if self.data.is_zero() { NoSign } else { Plus }; } } self } } impl<'a> Not for &'a BigInt { type Output = BigInt; fn not(self) -> BigInt { match self.sign { NoSign | Plus => BigInt::from_biguint(Minus, &self.data + 1u32), Minus => BigInt::from_biguint(Plus, &self.data - 1u32), } } } // + 1 & -ff = ...0 01 & ...f 01 = ...0 01 = + 1 // +ff & - 1 = ...0 ff & ...f ff = ...0 ff = +ff // answer is pos, has length of a fn bitand_pos_neg(a: &mut SmallVec<[BigDigit; VEC_SIZE]>, b: &[BigDigit]) { let mut carry_b = 1; for (ai, &bi) in a.iter_mut().zip(b.iter()) { let twos_b = negate_carry(bi, &mut carry_b); *ai &= twos_b; } debug_assert!(b.len() > a.len() || carry_b == 0); } // - 1 & +ff = ...f ff & ...0 ff = ...0 ff = +ff // -ff & + 1 = ...f 01 & ...0 01 = ...0 01 = + 1 // answer is pos, has length of b fn bitand_neg_pos(a: &mut SmallVec<[BigDigit; VEC_SIZE]>, b: &[BigDigit]) { let mut carry_a = 1; for (ai, &bi) in a.iter_mut().zip(b.iter()) { let twos_a = negate_carry(*ai, &mut carry_a); *ai = twos_a & bi; } debug_assert!(a.len() > b.len() || carry_a == 0); if a.len() > b.len() { a.truncate(b.len()); } else if b.len() > a.len() { let extra = &b[a.len()..]; a.extend(extra.iter().cloned()); } } // - 1 & -ff = ...f ff & ...f 01 = ...f 01 = - ff // -ff & - 1 = ...f 01 & ...f ff = ...f 01 = - ff // -ff & -fe = ...f 01 & ...f 02 = ...f 00 = -100 // answer is neg, has length of longest with a possible carry fn bitand_neg_neg(a: &mut SmallVec<[BigDigit; VEC_SIZE]>, b: &[BigDigit]) { let mut carry_a = 1; let mut carry_b = 1; let mut carry_and = 1; for (ai, &bi) in a.iter_mut().zip(b.iter()) { let twos_a = negate_carry(*ai, &mut carry_a); let twos_b = negate_carry(bi, &mut carry_b); *ai = negate_carry(twos_a & twos_b, &mut carry_and); } debug_assert!(a.len() > b.len() || carry_a == 0); debug_assert!(b.len() > a.len() || carry_b == 0); if a.len() > b.len() { for ai in a[b.len()..].iter_mut() { let twos_a = negate_carry(*ai, &mut carry_a); *ai = negate_carry(twos_a, &mut carry_and); } debug_assert!(carry_a == 0); } else if b.len() > a.len() { let extra = &b[a.len()..]; a.extend(extra.iter().map(|&bi| { let twos_b = negate_carry(bi, &mut carry_b); negate_carry(twos_b, &mut carry_and) })); debug_assert!(carry_b == 0); } if carry_and != 0 { a.push(1); } } forward_val_val_binop!(impl BitAnd for BigInt, bitand); forward_ref_val_binop!(impl BitAnd for BigInt, bitand); // do not use forward_ref_ref_binop_commutative! for bitand so that we can // clone as needed, avoiding over-allocation impl<'a, 'b> BitAnd<&'b BigInt> for &'a BigInt { type Output = BigInt; #[inline] fn bitand(self, other: &BigInt) -> BigInt { match (self.sign, other.sign) { (NoSign, _) | (_, NoSign) => BigInt::from_slice(NoSign, &[]), (Plus, Plus) => BigInt::from_biguint(Plus, &self.data & &other.data), (Plus, Minus) => self.clone() & other, (Minus, Plus) => other.clone() & self, (Minus, Minus) => { // forward to val-ref, choosing the larger to clone if self.len() >= other.len() { self.clone() & other } else { other.clone() & self } } } } } impl<'a> BitAnd<&'a BigInt> for BigInt { type Output = BigInt; #[inline] fn bitand(mut self, other: &BigInt) -> BigInt { self &= other; self } } forward_val_assign!(impl BitAndAssign for BigInt, bitand_assign); impl<'a> BitAndAssign<&'a BigInt> for BigInt { fn bitand_assign(&mut self, other: &BigInt) { match (self.sign, other.sign) { (NoSign, _) => {} (_, NoSign) => self.assign_from_slice_native(NoSign, &[]), (Plus, Plus) => { self.data &= &other.data; if self.data.is_zero() { self.sign = NoSign; } } (Plus, Minus) => { bitand_pos_neg(self.digits_mut(), other.digits()); self.normalize(); } (Minus, Plus) => { bitand_neg_pos(self.digits_mut(), other.digits()); self.sign = Plus; self.normalize(); } (Minus, Minus) => { bitand_neg_neg(self.digits_mut(), other.digits()); self.normalize(); } } } } // + 1 | -ff = ...0 01 | ...f 01 = ...f 01 = -ff // +ff | - 1 = ...0 ff | ...f ff = ...f ff = - 1 // answer is neg, has length of b fn bitor_pos_neg(a: &mut SmallVec<[BigDigit; VEC_SIZE]>, b: &[BigDigit]) { let mut carry_b = 1; let mut carry_or = 1; for (ai, &bi) in a.iter_mut().zip(b.iter()) { let twos_b = negate_carry(bi, &mut carry_b); *ai = negate_carry(*ai | twos_b, &mut carry_or); } debug_assert!(b.len() > a.len() || carry_b == 0); if a.len() > b.len() { a.truncate(b.len()); } else if b.len() > a.len() { let extra = &b[a.len()..]; a.extend(extra.iter().map(|&bi| { let twos_b = negate_carry(bi, &mut carry_b); negate_carry(twos_b, &mut carry_or) })); debug_assert!(carry_b == 0); } // for carry_or to be non-zero, we would need twos_b == 0 debug_assert!(carry_or == 0); } // - 1 | +ff = ...f ff | ...0 ff = ...f ff = - 1 // -ff | + 1 = ...f 01 | ...0 01 = ...f 01 = -ff // answer is neg, has length of a fn bitor_neg_pos(a: &mut SmallVec<[BigDigit; VEC_SIZE]>, b: &[BigDigit]) { let mut carry_a = 1; let mut carry_or = 1; for (ai, &bi) in a.iter_mut().zip(b.iter()) { let twos_a = negate_carry(*ai, &mut carry_a); *ai = negate_carry(twos_a | bi, &mut carry_or); } debug_assert!(a.len() > b.len() || carry_a == 0); if a.len() > b.len() { for ai in a[b.len()..].iter_mut() { let twos_a = negate_carry(*ai, &mut carry_a); *ai = negate_carry(twos_a, &mut carry_or); } debug_assert!(carry_a == 0); } // for carry_or to be non-zero, we would need twos_a == 0 debug_assert!(carry_or == 0); } // - 1 | -ff = ...f ff | ...f 01 = ...f ff = -1 // -ff | - 1 = ...f 01 | ...f ff = ...f ff = -1 // answer is neg, has length of shortest fn bitor_neg_neg(a: &mut SmallVec<[BigDigit; VEC_SIZE]>, b: &[BigDigit]) { let mut carry_a = 1; let mut carry_b = 1; let mut carry_or = 1; for (ai, &bi) in a.iter_mut().zip(b.iter()) { let twos_a = negate_carry(*ai, &mut carry_a); let twos_b = negate_carry(bi, &mut carry_b); *ai = negate_carry(twos_a | twos_b, &mut carry_or); } debug_assert!(a.len() > b.len() || carry_a == 0); debug_assert!(b.len() > a.len() || carry_b == 0); if a.len() > b.len() { a.truncate(b.len()); } // for carry_or to be non-zero, we would need twos_a == 0 or twos_b == 0 debug_assert!(carry_or == 0); } forward_val_val_binop!(impl BitOr for BigInt, bitor); forward_ref_val_binop!(impl BitOr for BigInt, bitor); // do not use forward_ref_ref_binop_commutative! for bitor so that we can // clone as needed, avoiding over-allocation impl<'a, 'b> BitOr<&'b BigInt> for &'a BigInt { type Output = BigInt; #[inline] fn bitor(self, other: &BigInt) -> BigInt { match (self.sign, other.sign) { (NoSign, _) => other.clone(), (_, NoSign) => self.clone(), (Plus, Plus) => BigInt::from_biguint(Plus, &self.data | &other.data), (Plus, Minus) => other.clone() | self, (Minus, Plus) => self.clone() | other, (Minus, Minus) => { // forward to val-ref, choosing the smaller to clone if self.len() <= other.len() { self.clone() | other } else { other.clone() | self } } } } } impl<'a> BitOr<&'a BigInt> for BigInt { type Output = BigInt; #[inline] fn bitor(mut self, other: &BigInt) -> BigInt { self |= other; self } } forward_val_assign!(impl BitOrAssign for BigInt, bitor_assign); impl<'a> BitOrAssign<&'a BigInt> for BigInt { fn bitor_assign(&mut self, other: &BigInt) { match (self.sign, other.sign) { (_, NoSign) => {} (NoSign, _) => self.assign_from_slice_native(other.sign, other.digits()), (Plus, Plus) => self.data |= &other.data, (Plus, Minus) => { bitor_pos_neg(self.digits_mut(), other.digits()); self.sign = Minus; self.normalize(); } (Minus, Plus) => { bitor_neg_pos(self.digits_mut(), other.digits()); self.normalize(); } (Minus, Minus) => { bitor_neg_neg(self.digits_mut(), other.digits()); self.normalize(); } } } } // + 1 ^ -ff = ...0 01 ^ ...f 01 = ...f 00 = -100 // +ff ^ - 1 = ...0 ff ^ ...f ff = ...f 00 = -100 // answer is neg, has length of longest with a possible carry fn bitxor_pos_neg(a: &mut SmallVec<[BigDigit; VEC_SIZE]>, b: &[BigDigit]) { let mut carry_b = 1; let mut carry_xor = 1; for (ai, &bi) in a.iter_mut().zip(b.iter()) { let twos_b = negate_carry(bi, &mut carry_b); *ai = negate_carry(*ai ^ twos_b, &mut carry_xor); } debug_assert!(b.len() > a.len() || carry_b == 0); if a.len() > b.len() { for ai in a[b.len()..].iter_mut() { let twos_b = !0; *ai = negate_carry(*ai ^ twos_b, &mut carry_xor); } } else if b.len() > a.len() { let extra = &b[a.len()..]; a.extend(extra.iter().map(|&bi| { let twos_b = negate_carry(bi, &mut carry_b); negate_carry(twos_b, &mut carry_xor) })); debug_assert!(carry_b == 0); } if carry_xor != 0 { a.push(1); } } // - 1 ^ +ff = ...f ff ^ ...0 ff = ...f 00 = -100 // -ff ^ + 1 = ...f 01 ^ ...0 01 = ...f 00 = -100 // answer is neg, has length of longest with a possible carry fn bitxor_neg_pos(a: &mut SmallVec<[BigDigit; VEC_SIZE]>, b: &[BigDigit]) { let mut carry_a = 1; let mut carry_xor = 1; for (ai, &bi) in a.iter_mut().zip(b.iter()) { let twos_a = negate_carry(*ai, &mut carry_a); *ai = negate_carry(twos_a ^ bi, &mut carry_xor); } debug_assert!(a.len() > b.len() || carry_a == 0); if a.len() > b.len() { for ai in a[b.len()..].iter_mut() { let twos_a = negate_carry(*ai, &mut carry_a); *ai = negate_carry(twos_a, &mut carry_xor); } debug_assert!(carry_a == 0); } else if b.len() > a.len() { let extra = &b[a.len()..]; a.extend(extra.iter().map(|&bi| { let twos_a = !0; negate_carry(twos_a ^ bi, &mut carry_xor) })); } if carry_xor != 0 { a.push(1); } } // - 1 ^ -ff = ...f ff ^ ...f 01 = ...0 fe = +fe // -ff & - 1 = ...f 01 ^ ...f ff = ...0 fe = +fe // answer is pos, has length of longest fn bitxor_neg_neg(a: &mut SmallVec<[BigDigit; VEC_SIZE]>, b: &[BigDigit]) { let mut carry_a = 1; let mut carry_b = 1; for (ai, &bi) in a.iter_mut().zip(b.iter()) { let twos_a = negate_carry(*ai, &mut carry_a); let twos_b = negate_carry(bi, &mut carry_b); *ai = twos_a ^ twos_b; } debug_assert!(a.len() > b.len() || carry_a == 0); debug_assert!(b.len() > a.len() || carry_b == 0); if a.len() > b.len() { for ai in a[b.len()..].iter_mut() { let twos_a = negate_carry(*ai, &mut carry_a); let twos_b = !0; *ai = twos_a ^ twos_b; } debug_assert!(carry_a == 0); } else if b.len() > a.len() { let extra = &b[a.len()..]; a.extend(extra.iter().map(|&bi| { let twos_a = !0; let twos_b = negate_carry(bi, &mut carry_b); twos_a ^ twos_b })); debug_assert!(carry_b == 0); } } forward_all_binop_to_val_ref_commutative!(impl BitXor for BigInt, bitxor); impl<'a> BitXor<&'a BigInt> for BigInt { type Output = BigInt; #[inline] fn bitxor(mut self, other: &BigInt) -> BigInt { self ^= other; self } } forward_val_assign!(impl BitXorAssign for BigInt, bitxor_assign); impl<'a> BitXorAssign<&'a BigInt> for BigInt { fn bitxor_assign(&mut self, other: &BigInt) { match (self.sign, other.sign) { (_, NoSign) => {} (NoSign, _) => self.assign_from_slice_native(other.sign, other.digits()), (Plus, Plus) => { self.data ^= &other.data; if self.data.is_zero() { self.sign = NoSign; } } (Plus, Minus) => { bitxor_pos_neg(self.digits_mut(), other.digits()); self.sign = Minus; self.normalize(); } (Minus, Plus) => { bitxor_neg_pos(self.digits_mut(), other.digits()); self.normalize(); } (Minus, Minus) => { bitxor_neg_neg(self.digits_mut(), other.digits()); self.sign = Plus; self.normalize(); } } } } impl FromStr for BigInt { type Err = ParseBigIntError; #[inline] fn from_str(s: &str) -> Result { BigInt::from_str_radix(s, 10) } } impl Num for BigInt { type FromStrRadixErr = ParseBigIntError; /// Creates and initializes a BigInt. #[inline] fn from_str_radix(mut s: &str, radix: u32) -> Result { let sign = if s.starts_with('-') { let tail = &s[1..]; if !tail.starts_with('+') { s = tail } Minus } else { Plus }; let bu = BigUint::from_str_radix(s, radix)?; Ok(BigInt::from_biguint(sign, bu)) } } impl Shl for BigInt { type Output = BigInt; #[inline] fn shl(mut self, rhs: usize) -> BigInt { self <<= rhs; self } } impl<'a> Shl for &'a BigInt { type Output = BigInt; #[inline] fn shl(self, rhs: usize) -> BigInt { BigInt::from_biguint(self.sign, &self.data << rhs) } } impl ShlAssign for BigInt { #[inline] fn shl_assign(&mut self, rhs: usize) { self.data <<= rhs; } } // Negative values need a rounding adjustment if there are any ones in the // bits that are getting shifted out. fn shr_round_down(i: &BigInt, rhs: usize) -> bool { i.is_negative() && biguint::trailing_zeros(&i.data) .map(|n| n < rhs) .unwrap_or(false) } impl Shr for BigInt { type Output = BigInt; #[inline] fn shr(mut self, rhs: usize) -> BigInt { self >>= rhs; self } } impl<'a> Shr for &'a BigInt { type Output = BigInt; #[inline] fn shr(self, rhs: usize) -> BigInt { let round_down = shr_round_down(self, rhs); let data = &self.data >> rhs; BigInt::from_biguint(self.sign, if round_down { data + 1u8 } else { data }) } } impl ShrAssign for BigInt { #[inline] fn shr_assign(&mut self, rhs: usize) { let round_down = shr_round_down(self, rhs); self.data >>= rhs; if round_down { self.data += 1u8; } else if self.data.is_zero() { self.sign = NoSign; } } } impl Zero for BigInt { #[inline] fn zero() -> BigInt { BigInt::from_biguint(NoSign, Zero::zero()) } #[inline] fn is_zero(&self) -> bool { self.sign == NoSign } } impl One for BigInt { #[inline] fn one() -> BigInt { BigInt::from_biguint(Plus, One::one()) } #[inline] fn is_one(&self) -> bool { self.sign == Plus && self.data.is_one() } } impl Signed for BigInt { #[inline] fn abs(&self) -> BigInt { match self.sign { Plus | NoSign => self.clone(), Minus => BigInt::from_biguint(Plus, self.data.clone()), } } #[inline] fn abs_sub(&self, other: &BigInt) -> BigInt { if *self <= *other { Zero::zero() } else { self - other } } #[inline] fn signum(&self) -> BigInt { match self.sign { Plus => BigInt::from_biguint(Plus, One::one()), Minus => BigInt::from_biguint(Minus, One::one()), NoSign => Zero::zero(), } } #[inline] fn is_positive(&self) -> bool { self.sign == Plus } #[inline] fn is_negative(&self) -> bool { self.sign == Minus } } /// Help function for pow /// /// Computes the effect of the exponent on the sign. #[inline] fn powsign(sign: Sign, other: &T) -> Sign { if other.is_zero() { Plus } else if sign != Minus || other.is_odd() { sign } else { -sign } } macro_rules! pow_impl { ($T:ty) => { impl<'a> Pow<$T> for &'a BigInt { type Output = BigInt; #[inline] fn pow(self, rhs: $T) -> BigInt { BigInt::from_biguint(powsign(self.sign, &rhs), (&self.data).pow(rhs)) } } impl<'a, 'b> Pow<&'b $T> for &'a BigInt { type Output = BigInt; #[inline] fn pow(self, rhs: &$T) -> BigInt { BigInt::from_biguint(powsign(self.sign, rhs), (&self.data).pow(rhs)) } } }; } pow_impl!(u8); pow_impl!(u16); pow_impl!(u32); pow_impl!(u64); pow_impl!(usize); #[cfg(has_i128)] pow_impl!(u128); // A convenience method for getting the absolute value of an i32 in a u32. #[inline] fn i32_abs_as_u32(a: i32) -> u32 { if a == i32::min_value() { a as u32 } else { a.abs() as u32 } } // A convenience method for getting the absolute value of an i64 in a u64. #[inline] fn i64_abs_as_u64(a: i64) -> u64 { if a == i64::min_value() { a as u64 } else { a.abs() as u64 } } // A convenience method for getting the absolute value of an i128 in a u128. #[cfg(has_i128)] #[inline] fn i128_abs_as_u128(a: i128) -> u128 { if a == i128::min_value() { a as u128 } else { a.abs() as u128 } } // We want to forward to BigUint::add, but it's not clear how that will go until // we compare both sign and magnitude. So we duplicate this body for every // val/ref combination, deferring that decision to BigUint's own forwarding. macro_rules! bigint_add { ($a:expr, $a_owned:expr, $a_data:expr, $a_sign:expr, $b:expr, $b_owned:expr, $b_data:expr, $b_sign:expr) => { match ($a_sign, $b_sign) { (_, NoSign) => $a_owned, (NoSign, _) => $b_owned, // same sign => keep the sign with the sum of magnitudes (Plus, Plus) | (Minus, Minus) => BigInt::from_biguint($a_sign, $a_data + $b_data), // opposite signs => keep the sign of the larger with the difference of magnitudes (Plus, Minus) | (Minus, Plus) => match $a_data.cmp(&$b_data) { Less => BigInt::from_biguint($b_sign, $b_data - $a_data), Greater => BigInt::from_biguint($a.sign, $a_data - $b_data), Equal => Zero::zero(), }, } }; } impl<'a, 'b> Add<&'b BigInt> for &'a BigInt { type Output = BigInt; #[inline] fn add(self, other: &BigInt) -> BigInt { bigint_add!( self, self.clone(), &self.data, self.sign, other, other.clone(), &other.data, other.sign ) } } impl<'a> Add for &'a BigInt { type Output = BigInt; #[inline] fn add(self, other: BigInt) -> BigInt { bigint_add!( self, self.clone(), &self.data, self.sign, other, other, other.data, other.sign ) } } impl<'a> Add<&'a BigInt> for BigInt { type Output = BigInt; #[inline] fn add(self, other: &BigInt) -> BigInt { bigint_add!( self, self, self.data, self.sign, other, other.clone(), &other.data, other.sign ) } } impl<'a> Add<&'a mut BigInt> for BigInt { type Output = BigInt; #[inline] fn add(self, other: &mut BigInt) -> BigInt { bigint_add!( self, self, self.data, self.sign, other, other.clone(), &other.data, other.sign ) } } impl<'a, 'b> Add<&'a mut BigInt> for &'b mut BigInt { type Output = BigInt; #[inline] fn add(self, other: &mut BigInt) -> BigInt { bigint_add!( self, self.clone(), &self.data, self.sign, other, other.clone(), &other.data, other.sign ) } } impl<'a> Add<&'a BigUint> for BigInt { type Output = BigInt; #[inline] fn add(self, other: &BigUint) -> BigInt { bigint_add!( self, self, self.data, self.sign, other, other.to_bigint().unwrap(), other, Plus ) } } impl Add for BigInt { type Output = BigInt; #[inline] fn add(self, other: BigInt) -> BigInt { bigint_add!(self, self, self.data, self.sign, other, other, other.data, other.sign) } } impl<'a> AddAssign<&'a BigInt> for BigInt { #[inline] fn add_assign(&mut self, other: &BigInt) { let n = mem::replace(self, BigInt::zero()); *self = n + other; } } forward_val_assign!(impl AddAssign for BigInt, add_assign); promote_all_scalars!(impl Add for BigInt, add); promote_all_scalars_assign!(impl AddAssign for BigInt, add_assign); forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigInt, add); forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigInt, add); #[cfg(has_i128)] forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigInt, add); impl Add for BigInt { type Output = BigInt; #[inline] fn add(self, other: u32) -> BigInt { match self.sign { NoSign => From::from(other), Plus => BigInt::from_biguint(Plus, self.data + other), Minus => match self.data.cmp(&From::from(other)) { Equal => Zero::zero(), Less => BigInt::from_biguint(Plus, other - self.data), Greater => BigInt::from_biguint(Minus, self.data - other), }, } } } impl AddAssign for BigInt { #[inline] fn add_assign(&mut self, other: u32) { let n = mem::replace(self, BigInt::zero()); *self = n + other; } } impl Add for BigInt { type Output = BigInt; #[inline] fn add(self, other: u64) -> BigInt { match self.sign { NoSign => From::from(other), Plus => BigInt::from_biguint(Plus, self.data + other), Minus => match self.data.cmp(&From::from(other)) { Equal => Zero::zero(), Less => BigInt::from_biguint(Plus, other - self.data), Greater => BigInt::from_biguint(Minus, self.data - other), }, } } } impl AddAssign for BigInt { #[inline] fn add_assign(&mut self, other: u64) { let n = mem::replace(self, BigInt::zero()); *self = n + other; } } #[cfg(has_i128)] impl Add for BigInt { type Output = BigInt; #[inline] fn add(self, other: u128) -> BigInt { match self.sign { NoSign => From::from(other), Plus => BigInt::from_biguint(Plus, self.data + other), Minus => match self.data.cmp(&From::from(other)) { Equal => Zero::zero(), Less => BigInt::from_biguint(Plus, other - self.data), Greater => BigInt::from_biguint(Minus, self.data - other), }, } } } #[cfg(has_i128)] impl AddAssign for BigInt { #[inline] fn add_assign(&mut self, other: u128) { let n = mem::replace(self, BigInt::zero()); *self = n + other; } } forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigInt, add); forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigInt, add); #[cfg(has_i128)] forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigInt, add); impl Add for BigInt { type Output = BigInt; #[inline] fn add(self, other: i32) -> BigInt { if other >= 0 { self + other as u32 } else { self - i32_abs_as_u32(other) } } } impl AddAssign for BigInt { #[inline] fn add_assign(&mut self, other: i32) { if other >= 0 { *self += other as u32; } else { *self -= i32_abs_as_u32(other); } } } impl Add for BigInt { type Output = BigInt; #[inline] fn add(self, other: i64) -> BigInt { if other >= 0 { self + other as u64 } else { self - i64_abs_as_u64(other) } } } impl AddAssign for BigInt { #[inline] fn add_assign(&mut self, other: i64) { if other >= 0 { *self += other as u64; } else { *self -= i64_abs_as_u64(other); } } } #[cfg(has_i128)] impl Add for BigInt { type Output = BigInt; #[inline] fn add(self, other: i128) -> BigInt { if other >= 0 { self + other as u128 } else { self - i128_abs_as_u128(other) } } } #[cfg(has_i128)] impl AddAssign for BigInt { #[inline] fn add_assign(&mut self, other: i128) { if other >= 0 { *self += other as u128; } else { *self -= i128_abs_as_u128(other); } } } // We want to forward to BigUint::sub, but it's not clear how that will go until // we compare both sign and magnitude. So we duplicate this body for every // val/ref combination, deferring that decision to BigUint's own forwarding. macro_rules! bigint_sub { ($a:expr, $a_owned:expr, $a_data:expr, $b:expr, $b_owned:expr, $b_data:expr) => { match ($a.sign, $b.sign) { (_, NoSign) => $a_owned, (NoSign, _) => -$b_owned, // opposite signs => keep the sign of the left with the sum of magnitudes (Plus, Minus) | (Minus, Plus) => BigInt::from_biguint($a.sign, $a_data + $b_data), // same sign => keep or toggle the sign of the left with the difference of magnitudes (Plus, Plus) | (Minus, Minus) => match $a.data.cmp(&$b.data) { Less => BigInt::from_biguint(-$a.sign, $b_data - $a_data), Greater => BigInt::from_biguint($a.sign, $a_data - $b_data), Equal => Zero::zero(), }, } }; } impl<'a, 'b> Sub<&'b BigInt> for &'a BigInt { type Output = BigInt; #[inline] fn sub(self, other: &BigInt) -> BigInt { bigint_sub!( self, self.clone(), &self.data, other, other.clone(), &other.data ) } } impl<'a> Sub for &'a BigInt { type Output = BigInt; #[inline] fn sub(self, other: BigInt) -> BigInt { bigint_sub!(self, self.clone(), &self.data, other, other, other.data) } } impl<'a> Sub<&'a BigInt> for BigInt { type Output = BigInt; #[inline] fn sub(self, other: &BigInt) -> BigInt { bigint_sub!(self, self, self.data, other, other.clone(), &other.data) } } impl Sub for BigInt { type Output = BigInt; #[inline] fn sub(self, other: BigInt) -> BigInt { bigint_sub!(self, self, self.data, other, other, other.data) } } impl<'a> SubAssign<&'a BigInt> for BigInt { #[inline] fn sub_assign(&mut self, other: &BigInt) { let n = mem::replace(self, BigInt::zero()); *self = n - other; } } forward_val_assign!(impl SubAssign for BigInt, sub_assign); promote_all_scalars!(impl Sub for BigInt, sub); promote_all_scalars_assign!(impl SubAssign for BigInt, sub_assign); forward_all_scalar_binop_to_val_val!(impl Sub for BigInt, sub); forward_all_scalar_binop_to_val_val!(impl Sub for BigInt, sub); #[cfg(has_i128)] forward_all_scalar_binop_to_val_val!(impl Sub for BigInt, sub); impl Sub for BigInt { type Output = BigInt; #[inline] fn sub(self, other: u32) -> BigInt { match self.sign { NoSign => BigInt::from_biguint(Minus, From::from(other)), Minus => BigInt::from_biguint(Minus, self.data + other), Plus => match self.data.cmp(&From::from(other)) { Equal => Zero::zero(), Greater => BigInt::from_biguint(Plus, self.data - other), Less => BigInt::from_biguint(Minus, other - self.data), }, } } } impl SubAssign for BigInt { #[inline] fn sub_assign(&mut self, other: u32) { let n = mem::replace(self, BigInt::zero()); *self = n - other; } } impl Sub for u32 { type Output = BigInt; #[inline] fn sub(self, other: BigInt) -> BigInt { -(other - self) } } impl Sub for u64 { type Output = BigInt; #[inline] fn sub(self, other: BigInt) -> BigInt { -(other - self) } } #[cfg(has_i128)] impl Sub for u128 { type Output = BigInt; #[inline] fn sub(self, other: BigInt) -> BigInt { -(other - self) } } impl Sub for BigInt { type Output = BigInt; #[inline] fn sub(self, other: u64) -> BigInt { match self.sign { NoSign => BigInt::from_biguint(Minus, From::from(other)), Minus => BigInt::from_biguint(Minus, self.data + other), Plus => match self.data.cmp(&From::from(other)) { Equal => Zero::zero(), Greater => BigInt::from_biguint(Plus, self.data - other), Less => BigInt::from_biguint(Minus, other - self.data), }, } } } impl SubAssign for BigInt { #[inline] fn sub_assign(&mut self, other: u64) { let n = mem::replace(self, BigInt::zero()); *self = n - other; } } #[cfg(has_i128)] impl Sub for BigInt { type Output = BigInt; #[inline] fn sub(self, other: u128) -> BigInt { match self.sign { NoSign => BigInt::from_biguint(Minus, From::from(other)), Minus => BigInt::from_biguint(Minus, self.data + other), Plus => match self.data.cmp(&From::from(other)) { Equal => Zero::zero(), Greater => BigInt::from_biguint(Plus, self.data - other), Less => BigInt::from_biguint(Minus, other - self.data), }, } } } #[cfg(has_i128)] impl SubAssign for BigInt { #[inline] fn sub_assign(&mut self, other: u128) { let n = mem::replace(self, BigInt::zero()); *self = n - other; } } forward_all_scalar_binop_to_val_val!(impl Sub for BigInt, sub); forward_all_scalar_binop_to_val_val!(impl Sub for BigInt, sub); #[cfg(has_i128)] forward_all_scalar_binop_to_val_val!(impl Sub for BigInt, sub); impl Sub for BigInt { type Output = BigInt; #[inline] fn sub(self, other: i32) -> BigInt { if other >= 0 { self - other as u32 } else { self + i32_abs_as_u32(other) } } } impl SubAssign for BigInt { #[inline] fn sub_assign(&mut self, other: i32) { if other >= 0 { *self -= other as u32; } else { *self += i32_abs_as_u32(other); } } } impl Sub for i32 { type Output = BigInt; #[inline] fn sub(self, other: BigInt) -> BigInt { if self >= 0 { self as u32 - other } else { -other - i32_abs_as_u32(self) } } } impl Sub for BigInt { type Output = BigInt; #[inline] fn sub(self, other: i64) -> BigInt { if other >= 0 { self - other as u64 } else { self + i64_abs_as_u64(other) } } } impl SubAssign for BigInt { #[inline] fn sub_assign(&mut self, other: i64) { if other >= 0 { *self -= other as u64; } else { *self += i64_abs_as_u64(other); } } } impl Sub for i64 { type Output = BigInt; #[inline] fn sub(self, other: BigInt) -> BigInt { if self >= 0 { self as u64 - other } else { -other - i64_abs_as_u64(self) } } } #[cfg(has_i128)] impl Sub for BigInt { type Output = BigInt; #[inline] fn sub(self, other: i128) -> BigInt { if other >= 0 { self - other as u128 } else { self + i128_abs_as_u128(other) } } } #[cfg(has_i128)] impl SubAssign for BigInt { #[inline] fn sub_assign(&mut self, other: i128) { if other >= 0 { *self -= other as u128; } else { *self += i128_abs_as_u128(other); } } } #[cfg(has_i128)] impl Sub for i128 { type Output = BigInt; #[inline] fn sub(self, other: BigInt) -> BigInt { if self >= 0 { self as u128 - other } else { -other - i128_abs_as_u128(self) } } } forward_all_binop_to_ref_ref!(impl Mul for BigInt, mul); impl<'a, 'b> Mul<&'b BigInt> for &'a BigInt { type Output = BigInt; #[inline] fn mul(self, other: &BigInt) -> BigInt { BigInt::from_biguint(self.sign * other.sign, &self.data * &other.data) } } impl<'a> MulAssign<&'a BigInt> for BigInt { #[inline] fn mul_assign(&mut self, other: &BigInt) { *self = &*self * other; } } forward_val_assign!(impl MulAssign for BigInt, mul_assign); promote_all_scalars!(impl Mul for BigInt, mul); promote_all_scalars_assign!(impl MulAssign for BigInt, mul_assign); forward_all_scalar_binop_to_val_val_commutative!(impl Mul for BigInt, mul); forward_all_scalar_binop_to_val_val_commutative!(impl Mul for BigInt, mul); #[cfg(has_i128)] forward_all_scalar_binop_to_val_val_commutative!(impl Mul for BigInt, mul); impl Mul for BigInt { type Output = BigInt; #[inline] fn mul(self, other: u32) -> BigInt { BigInt::from_biguint(self.sign, self.data * other) } } impl MulAssign for BigInt { #[inline] fn mul_assign(&mut self, other: u32) { self.data *= other; if self.data.is_zero() { self.sign = NoSign; } } } impl Mul for BigInt { type Output = BigInt; #[inline] fn mul(self, other: u64) -> BigInt { BigInt::from_biguint(self.sign, self.data * other) } } impl MulAssign for BigInt { #[inline] fn mul_assign(&mut self, other: u64) { self.data *= other; if self.data.is_zero() { self.sign = NoSign; } } } #[cfg(has_i128)] impl Mul for BigInt { type Output = BigInt; #[inline] fn mul(self, other: u128) -> BigInt { BigInt::from_biguint(self.sign, self.data * other) } } #[cfg(has_i128)] impl MulAssign for BigInt { #[inline] fn mul_assign(&mut self, other: u128) { self.data *= other; if self.data.is_zero() { self.sign = NoSign; } } } forward_all_scalar_binop_to_val_val_commutative!(impl Mul for BigInt, mul); forward_all_scalar_binop_to_val_val_commutative!(impl Mul for BigInt, mul); #[cfg(has_i128)] forward_all_scalar_binop_to_val_val_commutative!(impl Mul for BigInt, mul); impl Mul for BigInt { type Output = BigInt; #[inline] fn mul(self, other: i32) -> BigInt { if other >= 0 { self * other as u32 } else { -(self * i32_abs_as_u32(other)) } } } impl MulAssign for BigInt { #[inline] fn mul_assign(&mut self, other: i32) { if other >= 0 { *self *= other as u32; } else { self.sign = -self.sign; *self *= i32_abs_as_u32(other); } } } impl Mul for BigInt { type Output = BigInt; #[inline] fn mul(self, other: i64) -> BigInt { if other >= 0 { self * other as u64 } else { -(self * i64_abs_as_u64(other)) } } } impl MulAssign for BigInt { #[inline] fn mul_assign(&mut self, other: i64) { if other >= 0 { *self *= other as u64; } else { self.sign = -self.sign; *self *= i64_abs_as_u64(other); } } } #[cfg(has_i128)] impl Mul for BigInt { type Output = BigInt; #[inline] fn mul(self, other: i128) -> BigInt { if other >= 0 { self * other as u128 } else { -(self * i128_abs_as_u128(other)) } } } #[cfg(has_i128)] impl MulAssign for BigInt { #[inline] fn mul_assign(&mut self, other: i128) { if other >= 0 { *self *= other as u128; } else { self.sign = -self.sign; *self *= i128_abs_as_u128(other); } } } forward_all_binop_to_ref_ref!(impl Div for BigInt, div); impl<'a, 'b> Div<&'b BigInt> for &'a BigInt { type Output = BigInt; #[inline] fn div(self, other: &BigInt) -> BigInt { let (q, _) = self.div_rem(other); q } } impl<'a> DivAssign<&'a BigInt> for BigInt { #[inline] fn div_assign(&mut self, other: &BigInt) { *self = &*self / other; } } forward_val_assign!(impl DivAssign for BigInt, div_assign); promote_all_scalars!(impl Div for BigInt, div); promote_all_scalars_assign!(impl DivAssign for BigInt, div_assign); forward_all_scalar_binop_to_val_val!(impl Div for BigInt, div); forward_all_scalar_binop_to_val_val!(impl Div for BigInt, div); #[cfg(has_i128)] forward_all_scalar_binop_to_val_val!(impl Div for BigInt, div); impl Div for BigInt { type Output = BigInt; #[inline] fn div(self, other: u32) -> BigInt { BigInt::from_biguint(self.sign, self.data / other) } } impl DivAssign for BigInt { #[inline] fn div_assign(&mut self, other: u32) { self.data /= other; if self.data.is_zero() { self.sign = NoSign; } } } impl Div for u32 { type Output = BigInt; #[inline] fn div(self, other: BigInt) -> BigInt { BigInt::from_biguint(other.sign, self / other.data) } } impl Div for BigInt { type Output = BigInt; #[inline] fn div(self, other: u64) -> BigInt { BigInt::from_biguint(self.sign, self.data / other) } } impl DivAssign for BigInt { #[inline] fn div_assign(&mut self, other: u64) { self.data /= other; if self.data.is_zero() { self.sign = NoSign; } } } impl Div for u64 { type Output = BigInt; #[inline] fn div(self, other: BigInt) -> BigInt { BigInt::from_biguint(other.sign, self / other.data) } } #[cfg(has_i128)] impl Div for BigInt { type Output = BigInt; #[inline] fn div(self, other: u128) -> BigInt { BigInt::from_biguint(self.sign, self.data / other) } } #[cfg(has_i128)] impl DivAssign for BigInt { #[inline] fn div_assign(&mut self, other: u128) { self.data /= other; if self.data.is_zero() { self.sign = NoSign; } } } #[cfg(has_i128)] impl Div for u128 { type Output = BigInt; #[inline] fn div(self, other: BigInt) -> BigInt { BigInt::from_biguint(other.sign, self / other.data) } } forward_all_scalar_binop_to_val_val!(impl Div for BigInt, div); forward_all_scalar_binop_to_val_val!(impl Div for BigInt, div); #[cfg(has_i128)] forward_all_scalar_binop_to_val_val!(impl Div for BigInt, div); impl Div for BigInt { type Output = BigInt; #[inline] fn div(self, other: i32) -> BigInt { if other >= 0 { self / other as u32 } else { -(self / i32_abs_as_u32(other)) } } } impl DivAssign for BigInt { #[inline] fn div_assign(&mut self, other: i32) { if other >= 0 { *self /= other as u32; } else { self.sign = -self.sign; *self /= i32_abs_as_u32(other); } } } impl Div for i32 { type Output = BigInt; #[inline] fn div(self, other: BigInt) -> BigInt { if self >= 0 { self as u32 / other } else { -(i32_abs_as_u32(self) / other) } } } impl Div for BigInt { type Output = BigInt; #[inline] fn div(self, other: i64) -> BigInt { if other >= 0 { self / other as u64 } else { -(self / i64_abs_as_u64(other)) } } } impl DivAssign for BigInt { #[inline] fn div_assign(&mut self, other: i64) { if other >= 0 { *self /= other as u64; } else { self.sign = -self.sign; *self /= i64_abs_as_u64(other); } } } impl Div for i64 { type Output = BigInt; #[inline] fn div(self, other: BigInt) -> BigInt { if self >= 0 { self as u64 / other } else { -(i64_abs_as_u64(self) / other) } } } #[cfg(has_i128)] impl Div for BigInt { type Output = BigInt; #[inline] fn div(self, other: i128) -> BigInt { if other >= 0 { self / other as u128 } else { -(self / i128_abs_as_u128(other)) } } } #[cfg(has_i128)] impl DivAssign for BigInt { #[inline] fn div_assign(&mut self, other: i128) { if other >= 0 { *self /= other as u128; } else { self.sign = -self.sign; *self /= i128_abs_as_u128(other); } } } #[cfg(has_i128)] impl Div for i128 { type Output = BigInt; #[inline] fn div(self, other: BigInt) -> BigInt { if self >= 0 { self as u128 / other } else { -(i128_abs_as_u128(self) / other) } } } forward_all_binop_to_ref_ref!(impl Rem for BigInt, rem); impl<'a, 'b> Rem<&'b BigInt> for &'a BigInt { type Output = BigInt; #[inline] fn rem(self, other: &BigInt) -> BigInt { let (_, r) = self.div_rem(other); r } } impl<'a> RemAssign<&'a BigInt> for BigInt { #[inline] fn rem_assign(&mut self, other: &BigInt) { *self = &*self % other; } } forward_val_assign!(impl RemAssign for BigInt, rem_assign); promote_all_scalars!(impl Rem for BigInt, rem); promote_all_scalars_assign!(impl RemAssign for BigInt, rem_assign); forward_all_scalar_binop_to_val_val!(impl Rem for BigInt, rem); forward_all_scalar_binop_to_val_val!(impl Rem for BigInt, rem); #[cfg(has_i128)] forward_all_scalar_binop_to_val_val!(impl Rem for BigInt, rem); impl Rem for BigInt { type Output = BigInt; #[inline] fn rem(self, other: u32) -> BigInt { BigInt::from_biguint(self.sign, self.data % other) } } impl RemAssign for BigInt { #[inline] fn rem_assign(&mut self, other: u32) { self.data %= other; if self.data.is_zero() { self.sign = NoSign; } } } impl Rem for u32 { type Output = BigInt; #[inline] fn rem(self, other: BigInt) -> BigInt { BigInt::from_biguint(Plus, self % other.data) } } impl Rem for BigInt { type Output = BigInt; #[inline] fn rem(self, other: u64) -> BigInt { BigInt::from_biguint(self.sign, self.data % other) } } impl RemAssign for BigInt { #[inline] fn rem_assign(&mut self, other: u64) { self.data %= other; if self.data.is_zero() { self.sign = NoSign; } } } impl Rem for u64 { type Output = BigInt; #[inline] fn rem(self, other: BigInt) -> BigInt { BigInt::from_biguint(Plus, self % other.data) } } #[cfg(has_i128)] impl Rem for BigInt { type Output = BigInt; #[inline] fn rem(self, other: u128) -> BigInt { BigInt::from_biguint(self.sign, self.data % other) } } #[cfg(has_i128)] impl RemAssign for BigInt { #[inline] fn rem_assign(&mut self, other: u128) { self.data %= other; if self.data.is_zero() { self.sign = NoSign; } } } #[cfg(has_i128)] impl Rem for u128 { type Output = BigInt; #[inline] fn rem(self, other: BigInt) -> BigInt { BigInt::from_biguint(Plus, self % other.data) } } forward_all_scalar_binop_to_val_val!(impl Rem for BigInt, rem); forward_all_scalar_binop_to_val_val!(impl Rem for BigInt, rem); #[cfg(has_i128)] forward_all_scalar_binop_to_val_val!(impl Rem for BigInt, rem); impl Rem for BigInt { type Output = BigInt; #[inline] fn rem(self, other: i32) -> BigInt { if other >= 0 { self % other as u32 } else { self % i32_abs_as_u32(other) } } } impl RemAssign for BigInt { #[inline] fn rem_assign(&mut self, other: i32) { if other >= 0 { *self %= other as u32; } else { *self %= i32_abs_as_u32(other); } } } impl Rem for i32 { type Output = BigInt; #[inline] fn rem(self, other: BigInt) -> BigInt { if self >= 0 { self as u32 % other } else { -(i32_abs_as_u32(self) % other) } } } impl Rem for BigInt { type Output = BigInt; #[inline] fn rem(self, other: i64) -> BigInt { if other >= 0 { self % other as i64 } else { self % i64_abs_as_u64(other) } } } impl RemAssign for BigInt { #[inline] fn rem_assign(&mut self, other: i64) { if other >= 0 { *self %= other as u64; } else { *self %= i64_abs_as_u64(other); } } } impl Rem for i64 { type Output = BigInt; #[inline] fn rem(self, other: BigInt) -> BigInt { if self >= 0 { self as u64 % other } else { -(i64_abs_as_u64(self) % other) } } } #[cfg(has_i128)] impl Rem for BigInt { type Output = BigInt; #[inline] fn rem(self, other: i128) -> BigInt { if other >= 0 { self % other as u128 } else { self % i128_abs_as_u128(other) } } } #[cfg(has_i128)] impl RemAssign for BigInt { #[inline] fn rem_assign(&mut self, other: i128) { if other >= 0 { *self %= other as u128; } else { *self %= i128_abs_as_u128(other); } } } #[cfg(has_i128)] impl Rem for i128 { type Output = BigInt; #[inline] fn rem(self, other: BigInt) -> BigInt { if self >= 0 { self as u128 % other } else { -(i128_abs_as_u128(self) % other) } } } impl Neg for BigInt { type Output = BigInt; #[inline] fn neg(mut self) -> BigInt { self.sign = -self.sign; self } } impl<'a> Neg for &'a BigInt { type Output = BigInt; #[inline] fn neg(self) -> BigInt { -self.clone() } } impl CheckedAdd for BigInt { #[inline] fn checked_add(&self, v: &BigInt) -> Option { Some(self.add(v)) } } impl CheckedSub for BigInt { #[inline] fn checked_sub(&self, v: &BigInt) -> Option { Some(self.sub(v)) } } impl CheckedMul for BigInt { #[inline] fn checked_mul(&self, v: &BigInt) -> Option { Some(self.mul(v)) } } impl CheckedDiv for BigInt { #[inline] fn checked_div(&self, v: &BigInt) -> Option { if v.is_zero() { None } else { Some(self.div(v)) } } } impl Integer for BigInt { #[inline] fn div_rem(&self, other: &BigInt) -> (BigInt, BigInt) { // r.sign == self.sign let (d_ui, r_ui) = self.data.div_mod_floor(&other.data); let d = BigInt::from_biguint(self.sign, d_ui); let r = BigInt::from_biguint(self.sign, r_ui); if other.is_negative() { (-d, r) } else { (d, r) } } #[inline] fn div_floor(&self, other: &BigInt) -> BigInt { let (d, _) = self.div_mod_floor(other); d } #[inline] fn mod_floor(&self, other: &BigInt) -> BigInt { let (_, m) = self.div_mod_floor(other); m } fn div_mod_floor(&self, other: &BigInt) -> (BigInt, BigInt) { // m.sign == other.sign let (d_ui, m_ui) = self.data.div_rem(&other.data); let d = BigInt::from_biguint(Plus, d_ui); let m = BigInt::from_biguint(Plus, m_ui); let one: BigInt = One::one(); match (self.sign, other.sign) { (_, NoSign) => panic!(), (Plus, Plus) | (NoSign, Plus) => (d, m), (Plus, Minus) | (NoSign, Minus) => { if m.is_zero() { (-d, Zero::zero()) } else { (-d - one, m + other) } } (Minus, Plus) => { if m.is_zero() { (-d, Zero::zero()) } else { (-d - one, other - m) } } (Minus, Minus) => (d, -m), } } /// Calculates the Greatest Common Divisor (GCD) of the number and `other`. /// /// The result is always positive. #[inline] fn gcd(&self, other: &BigInt) -> BigInt { BigInt::from_biguint(Plus, self.data.gcd(&other.data)) } /// Calculates the Lowest Common Multiple (LCM) of the number and `other`. #[inline] fn lcm(&self, other: &BigInt) -> BigInt { BigInt::from_biguint(Plus, self.data.lcm(&other.data)) } /// Deprecated, use `is_multiple_of` instead. #[inline] fn divides(&self, other: &BigInt) -> bool { self.is_multiple_of(other) } /// Returns `true` if the number is a multiple of `other`. #[inline] fn is_multiple_of(&self, other: &BigInt) -> bool { self.data.is_multiple_of(&other.data) } /// Returns `true` if the number is divisible by `2`. #[inline] fn is_even(&self) -> bool { self.data.is_even() } /// Returns `true` if the number is not divisible by `2`. #[inline] fn is_odd(&self) -> bool { self.data.is_odd() } } impl Roots for BigInt { fn nth_root(&self, n: u32) -> Self { assert!( !(self.is_negative() && n.is_even()), "root of degree {} is imaginary", n ); BigInt::from_biguint(self.sign, self.data.nth_root(n)) } fn sqrt(&self) -> Self { assert!(!self.is_negative(), "square root is imaginary"); BigInt::from_biguint(self.sign, self.data.sqrt()) } fn cbrt(&self) -> Self { BigInt::from_biguint(self.sign, self.data.cbrt()) } } impl ToPrimitive for BigInt { #[inline] fn to_i64(&self) -> Option { match self.sign { Plus => self.data.to_i64(), NoSign => Some(0), Minus => self.data.to_u64().and_then(|n| { let m: u64 = 1 << 63; if n < m { Some(-(n as i64)) } else if n == m { Some(i64::MIN) } else { None } }), } } #[inline] #[cfg(has_i128)] fn to_i128(&self) -> Option { match self.sign { Plus => self.data.to_i128(), NoSign => Some(0), Minus => self.data.to_u128().and_then(|n| { let m: u128 = 1 << 127; if n < m { Some(-(n as i128)) } else if n == m { Some(i128::MIN) } else { None } }), } } #[inline] fn to_u64(&self) -> Option { match self.sign { Plus => self.data.to_u64(), NoSign => Some(0), Minus => None, } } #[inline] #[cfg(has_i128)] fn to_u128(&self) -> Option { match self.sign { Plus => self.data.to_u128(), NoSign => Some(0), Minus => None, } } #[inline] fn to_f32(&self) -> Option { self.data .to_f32() .map(|n| if self.sign == Minus { -n } else { n }) } #[inline] fn to_f64(&self) -> Option { self.data .to_f64() .map(|n| if self.sign == Minus { -n } else { n }) } } impl FromPrimitive for BigInt { #[inline] fn from_i64(n: i64) -> Option { Some(BigInt::from(n)) } #[inline] #[cfg(has_i128)] fn from_i128(n: i128) -> Option { Some(BigInt::from(n)) } #[inline] fn from_u64(n: u64) -> Option { Some(BigInt::from(n)) } #[inline] #[cfg(has_i128)] fn from_u128(n: u128) -> Option { Some(BigInt::from(n)) } #[inline] fn from_f64(n: f64) -> Option { if n >= 0.0 { BigUint::from_f64(n).map(|x| BigInt::from_biguint(Plus, x)) } else { BigUint::from_f64(-n).map(|x| BigInt::from_biguint(Minus, x)) } } } impl From for BigInt { #[inline] fn from(n: i64) -> Self { if n >= 0 { BigInt::from(n as u64) } else { let u = u64::MAX - (n as u64) + 1; BigInt { sign: Minus, data: BigUint::from(u), } } } } #[cfg(has_i128)] impl From for BigInt { #[inline] fn from(n: i128) -> Self { if n >= 0 { BigInt::from(n as u128) } else { let u = u128::MAX - (n as u128) + 1; BigInt { sign: Minus, data: BigUint::from(u), } } } } macro_rules! impl_bigint_from_int { ($T:ty) => { impl From<$T> for BigInt { #[inline] fn from(n: $T) -> Self { BigInt::from(n as i64) } } }; } impl_bigint_from_int!(i8); impl_bigint_from_int!(i16); impl_bigint_from_int!(i32); impl_bigint_from_int!(isize); impl From for BigInt { #[inline] fn from(n: u64) -> Self { if n > 0 { BigInt { sign: Plus, data: BigUint::from(n), } } else { BigInt::zero() } } } #[cfg(has_i128)] impl From for BigInt { #[inline] fn from(n: u128) -> Self { if n > 0 { BigInt { sign: Plus, data: BigUint::from(n), } } else { BigInt::zero() } } } macro_rules! impl_bigint_from_uint { ($T:ty) => { impl From<$T> for BigInt { #[inline] fn from(n: $T) -> Self { BigInt::from(n as u64) } } }; } impl_bigint_from_uint!(u8); impl_bigint_from_uint!(u16); impl_bigint_from_uint!(u32); impl_bigint_from_uint!(usize); impl From for BigInt { #[inline] fn from(n: BigUint) -> Self { if n.is_zero() { BigInt::zero() } else { BigInt { sign: Plus, data: n, } } } } impl IntDigits for BigInt { #[inline] fn digits(&self) -> &[BigDigit] { self.data.digits() } #[inline] fn digits_mut(&mut self) -> &mut SmallVec<[BigDigit; VEC_SIZE]> { self.data.digits_mut() } #[inline] fn normalize(&mut self) { self.data.normalize(); if self.data.is_zero() { self.sign = NoSign; } } #[inline] fn capacity(&self) -> usize { self.data.capacity() } #[inline] fn len(&self) -> usize { self.data.len() } } #[cfg(feature = "serde")] impl serde::Serialize for BigInt { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer, { // Note: do not change the serialization format, or it may break // forward and backward compatibility of serialized data! (self.sign, &self.data).serialize(serializer) } } #[cfg(feature = "serde")] impl<'de> serde::Deserialize<'de> for BigInt { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, { let (sign, data) = serde::Deserialize::deserialize(deserializer)?; Ok(BigInt::from_biguint(sign, data)) } } /// A generic trait for converting a value to a `BigInt`. pub trait ToBigInt { /// Converts the value of `self` to a `BigInt`. fn to_bigint(&self) -> Option; } impl ToBigInt for BigInt { #[inline] fn to_bigint(&self) -> Option { Some(self.clone()) } } /// A generic trait for converting a value to a `BigInt`, consuming the value. pub trait IntoBigInt { /// Converts the value of `self` to a `BigInt`. fn into_bigint(self) -> Option; } impl IntoBigInt for BigInt { #[inline] fn into_bigint(self) -> Option { Some(self) } } impl ToBigInt for BigUint { #[inline] fn to_bigint(&self) -> Option { if self.is_zero() { Some(Zero::zero()) } else { Some(BigInt { sign: Plus, data: self.clone(), }) } } } impl biguint::ToBigUint for BigInt { #[inline] fn to_biguint(&self) -> Option { match self.sign() { Plus => Some(self.data.clone()), NoSign => Some(Zero::zero()), Minus => None, } } } impl IntoBigInt for BigUint { #[inline] fn into_bigint(self) -> Option { if self.is_zero() { Some(Zero::zero()) } else { Some(BigInt { sign: Plus, data: self, }) } } } impl IntoBigUint for BigInt { #[inline] fn into_biguint(self) -> Option { match self.sign() { Plus => Some(self.data), NoSign => Some(Zero::zero()), Minus => None, } } } macro_rules! impl_to_bigint { ($T:ty, $from_ty:path) => { impl ToBigInt for $T { #[inline] fn to_bigint(&self) -> Option { $from_ty(*self) } } impl IntoBigInt for $T { #[inline] fn into_bigint(self) -> Option { $from_ty(self) } } }; } impl_to_bigint!(isize, FromPrimitive::from_isize); impl_to_bigint!(i8, FromPrimitive::from_i8); impl_to_bigint!(i16, FromPrimitive::from_i16); impl_to_bigint!(i32, FromPrimitive::from_i32); impl_to_bigint!(i64, FromPrimitive::from_i64); #[cfg(has_i128)] impl_to_bigint!(i128, FromPrimitive::from_i128); impl_to_bigint!(usize, FromPrimitive::from_usize); impl_to_bigint!(u8, FromPrimitive::from_u8); impl_to_bigint!(u16, FromPrimitive::from_u16); impl_to_bigint!(u32, FromPrimitive::from_u32); impl_to_bigint!(u64, FromPrimitive::from_u64); #[cfg(has_i128)] impl_to_bigint!(u128, FromPrimitive::from_u128); impl_to_bigint!(f32, FromPrimitive::from_f32); impl_to_bigint!(f64, FromPrimitive::from_f64); /// Negates the sign of BigInt. /// #[inline] pub fn negate_sign(i: &mut BigInt) { i.sign = i.sign.neg(); } impl BigInt { /// Creates and initializes a BigInt. /// /// The digits are in little-endian base 232. #[inline] pub fn new(sign: Sign, digits: Vec) -> BigInt { BigInt::from_biguint(sign, BigUint::new(digits)) } // /// Negates the sign of BigInt. // /// // #[inline] // pub fn negate_sign(&mut self) { // println!("negate_sign: {:?}", self); // self.sign = self.sign.neg(); // println!("negate_sign: {:?}", self); // } /// Creates and initializes a `BigInt`. /// /// The digits are in little-endian base 232. #[inline] pub fn from_biguint(mut sign: Sign, mut data: BigUint) -> BigInt { if sign == NoSign { data.assign_from_slice(&[]); } else if data.is_zero() { sign = NoSign; } BigInt { sign, data } } /// Creates and initializes a `BigInt`. #[inline] pub fn from_slice(sign: Sign, slice: &[u32]) -> BigInt { BigInt::from_biguint(sign, BigUint::from_slice(slice)) } /// Creates and initializes a `BigInt` using `BigDigit`s. #[inline] pub fn from_slice_native(sign: Sign, slice: &[BigDigit]) -> BigInt { BigInt::from_biguint(sign, BigUint::from_slice_native(slice)) } /// Reinitializes a `BigInt`. #[inline] pub fn assign_from_slice(&mut self, sign: Sign, slice: &[u32]) { if sign == NoSign { self.data.assign_from_slice(&[]); self.sign = NoSign; } else { self.data.assign_from_slice(slice); self.sign = match self.data.is_zero() { true => NoSign, false => sign, } } } /// Reinitializes a `BigInt`, using native `BigDigit`s. #[inline] pub fn assign_from_slice_native(&mut self, sign: Sign, slice: &[BigDigit]) { if sign == NoSign { self.data.assign_from_slice_native(&[]); self.sign = NoSign; } else { self.data.assign_from_slice_native(slice); self.sign = match self.data.is_zero() { true => NoSign, false => sign, } } } /// Creates and initializes a `BigInt`. /// /// The bytes are in big-endian byte order. /// /// # Examples /// /// ``` /// use num_bigint_dig::{BigInt, Sign}; /// /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"A"), /// BigInt::parse_bytes(b"65", 10).unwrap()); /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AA"), /// BigInt::parse_bytes(b"16705", 10).unwrap()); /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AB"), /// BigInt::parse_bytes(b"16706", 10).unwrap()); /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"Hello world!"), /// BigInt::parse_bytes(b"22405534230753963835153736737", 10).unwrap()); /// ``` #[inline] pub fn from_bytes_be(sign: Sign, bytes: &[u8]) -> BigInt { BigInt::from_biguint(sign, BigUint::from_bytes_be(bytes)) } /// Creates and initializes a `BigInt`. /// /// The bytes are in little-endian byte order. #[inline] pub fn from_bytes_le(sign: Sign, bytes: &[u8]) -> BigInt { BigInt::from_biguint(sign, BigUint::from_bytes_le(bytes)) } /// Creates and initializes a `BigInt` from an array of bytes in /// two's complement binary representation. /// /// The digits are in big-endian base 28. #[inline] pub fn from_signed_bytes_be(digits: &[u8]) -> BigInt { let sign = match digits.first() { Some(v) if *v > 0x7f => Sign::Minus, Some(_) => Sign::Plus, None => return BigInt::zero(), }; if sign == Sign::Minus { // two's-complement the content to retrieve the magnitude let mut digits = Vec::from(digits); twos_complement_be(&mut digits); BigInt::from_biguint(sign, BigUint::from_bytes_be(&*digits)) } else { BigInt::from_biguint(sign, BigUint::from_bytes_be(digits)) } } /// Creates and initializes a `BigInt` from an array of bytes in two's complement. /// /// The digits are in little-endian base 28. #[inline] pub fn from_signed_bytes_le(digits: &[u8]) -> BigInt { let sign = match digits.last() { Some(v) if *v > 0x7f => Sign::Minus, Some(_) => Sign::Plus, None => return BigInt::zero(), }; if sign == Sign::Minus { // two's-complement the content to retrieve the magnitude let mut digits = Vec::from(digits); twos_complement_le(&mut digits); BigInt::from_biguint(sign, BigUint::from_bytes_le(&*digits)) } else { BigInt::from_biguint(sign, BigUint::from_bytes_le(digits)) } } /// Creates and initializes a `BigInt`. /// /// # Examples /// /// ``` /// use num_bigint_dig::{BigInt, ToBigInt}; /// /// assert_eq!(BigInt::parse_bytes(b"1234", 10), ToBigInt::to_bigint(&1234)); /// assert_eq!(BigInt::parse_bytes(b"ABCD", 16), ToBigInt::to_bigint(&0xABCD)); /// assert_eq!(BigInt::parse_bytes(b"G", 16), None); /// ``` #[inline] pub fn parse_bytes(buf: &[u8], radix: u32) -> Option { str::from_utf8(buf) .ok() .and_then(|s| BigInt::from_str_radix(s, radix).ok()) } /// Creates and initializes a `BigInt`. Each u8 of the input slice is /// interpreted as one digit of the number /// and must therefore be less than `radix`. /// /// The bytes are in big-endian byte order. /// `radix` must be in the range `2...256`. /// /// # Examples /// /// ``` /// use num_bigint_dig::{BigInt, Sign}; /// /// let inbase190 = vec![15, 33, 125, 12, 14]; /// let a = BigInt::from_radix_be(Sign::Minus, &inbase190, 190).unwrap(); /// assert_eq!(a.to_radix_be(190), (Sign:: Minus, inbase190)); /// ``` pub fn from_radix_be(sign: Sign, buf: &[u8], radix: u32) -> Option { BigUint::from_radix_be(buf, radix).map(|u| BigInt::from_biguint(sign, u)) } /// Creates and initializes a `BigInt`. Each u8 of the input slice is /// interpreted as one digit of the number /// and must therefore be less than `radix`. /// /// The bytes are in little-endian byte order. /// `radix` must be in the range `2...256`. /// /// # Examples /// /// ``` /// use num_bigint_dig::{BigInt, Sign}; /// /// let inbase190 = vec![14, 12, 125, 33, 15]; /// let a = BigInt::from_radix_be(Sign::Minus, &inbase190, 190).unwrap(); /// assert_eq!(a.to_radix_be(190), (Sign::Minus, inbase190)); /// ``` pub fn from_radix_le(sign: Sign, buf: &[u8], radix: u32) -> Option { BigUint::from_radix_le(buf, radix).map(|u| BigInt::from_biguint(sign, u)) } /// Returns the sign and the byte representation of the `BigInt` in big-endian byte order. /// /// # Examples /// /// ``` /// use num_bigint_dig::{ToBigInt, Sign}; /// /// let i = -1125.to_bigint().unwrap(); /// assert_eq!(i.to_bytes_be(), (Sign::Minus, vec![4, 101])); /// ``` #[inline] pub fn to_bytes_be(&self) -> (Sign, Vec) { (self.sign, self.data.to_bytes_be()) } /// Returns the sign and the byte representation of the `BigInt` in little-endian byte order. /// /// # Examples /// /// ``` /// use num_bigint_dig::{ToBigInt, Sign}; /// /// let i = -1125.to_bigint().unwrap(); /// assert_eq!(i.to_bytes_le(), (Sign::Minus, vec![101, 4])); /// ``` #[inline] pub fn to_bytes_le(&self) -> (Sign, Vec) { (self.sign, self.data.to_bytes_le()) } /// Returns the two's complement byte representation of the `BigInt` in big-endian byte order. /// /// # Examples /// /// ``` /// use num_bigint_dig::ToBigInt; /// /// let i = -1125.to_bigint().unwrap(); /// assert_eq!(i.to_signed_bytes_be(), vec![251, 155]); /// ``` #[inline] pub fn to_signed_bytes_be(&self) -> Vec { let mut bytes = self.data.to_bytes_be(); let first_byte = bytes.first().map(|v| *v).unwrap_or(0); if first_byte > 0x7f && !(first_byte == 0x80 && bytes.iter().skip(1).all(Zero::is_zero) && self.sign == Sign::Minus) { // msb used by magnitude, extend by 1 byte bytes.insert(0, 0); } if self.sign == Sign::Minus { twos_complement_be(&mut bytes); } bytes } /// Returns the two's complement byte representation of the `BigInt` in little-endian byte order. /// /// # Examples /// /// ``` /// use num_bigint_dig::ToBigInt; /// /// let i = -1125.to_bigint().unwrap(); /// assert_eq!(i.to_signed_bytes_le(), vec![155, 251]); /// ``` #[inline] pub fn to_signed_bytes_le(&self) -> Vec { let mut bytes = self.data.to_bytes_le(); let last_byte = bytes.last().map(|v| *v).unwrap_or(0); if last_byte > 0x7f && !(last_byte == 0x80 && bytes.iter().rev().skip(1).all(Zero::is_zero) && self.sign == Sign::Minus) { // msb used by magnitude, extend by 1 byte bytes.push(0); } if self.sign == Sign::Minus { twos_complement_le(&mut bytes); } bytes } /// Returns the integer formatted as a string in the given radix. /// `radix` must be in the range `2...36`. /// /// # Examples /// /// ``` /// use num_bigint_dig::BigInt; /// /// let i = BigInt::parse_bytes(b"ff", 16).unwrap(); /// assert_eq!(i.to_str_radix(16), "ff"); /// ``` #[inline] pub fn to_str_radix(&self, radix: u32) -> String { let mut v = to_str_radix_reversed(&self.data, radix); if self.is_negative() { v.push(b'-'); } v.reverse(); unsafe { String::from_utf8_unchecked(v) } } /// Returns the integer in the requested base in big-endian digit order. /// The output is not given in a human readable alphabet but as a zero /// based u8 number. /// `radix` must be in the range `2...256`. /// /// # Examples /// /// ``` /// use num_bigint_dig::{BigInt, Sign}; /// /// assert_eq!(BigInt::from(-0xFFFFi64).to_radix_be(159), /// (Sign::Minus, vec![2, 94, 27])); /// // 0xFFFF = 65535 = 2*(159^2) + 94*159 + 27 /// ``` #[inline] pub fn to_radix_be(&self, radix: u32) -> (Sign, Vec) { (self.sign, self.data.to_radix_be(radix)) } /// Returns the integer in the requested base in little-endian digit order. /// The output is not given in a human readable alphabet but as a zero /// based u8 number. /// `radix` must be in the range `2...256`. /// /// # Examples /// /// ``` /// use num_bigint_dig::{BigInt, Sign}; /// /// assert_eq!(BigInt::from(-0xFFFFi64).to_radix_le(159), /// (Sign::Minus, vec![27, 94, 2])); /// // 0xFFFF = 65535 = 27 + 94*159 + 2*(159^2) /// ``` #[inline] pub fn to_radix_le(&self, radix: u32) -> (Sign, Vec) { (self.sign, self.data.to_radix_le(radix)) } /// Returns the sign of the `BigInt` as a `Sign`. /// /// # Examples /// /// ``` /// use num_bigint_dig::{ToBigInt, Sign}; /// /// assert_eq!(ToBigInt::to_bigint(&1234).unwrap().sign(), Sign::Plus); /// assert_eq!(ToBigInt::to_bigint(&-4321).unwrap().sign(), Sign::Minus); /// assert_eq!(ToBigInt::to_bigint(&0).unwrap().sign(), Sign::NoSign); /// ``` #[inline] pub fn sign(&self) -> Sign { self.sign } /// Determines the fewest bits necessary to express the `BigInt`, /// not including the sign. #[inline] pub fn bits(&self) -> usize { self.data.bits() } /// Converts this `BigInt` into a `BigUint`, if it's not negative. #[inline] pub fn to_biguint(&self) -> Option { match self.sign { Plus => Some(self.data.clone()), NoSign => Some(Zero::zero()), Minus => None, } } #[inline] pub fn checked_add(&self, v: &BigInt) -> Option { Some(self.add(v)) } #[inline] pub fn checked_sub(&self, v: &BigInt) -> Option { Some(self.sub(v)) } #[inline] pub fn checked_mul(&self, v: &BigInt) -> Option { Some(self.mul(v)) } #[inline] pub fn checked_div(&self, v: &BigInt) -> Option { if v.is_zero() { None } else { Some(self.div(v)) } } /// Returns `(self ^ exponent) mod modulus` /// /// Note that this rounds like `mod_floor`, not like the `%` operator, /// which makes a difference when given a negative `self` or `modulus`. /// The result will be in the interval `[0, modulus)` for `modulus > 0`, /// or in the interval `(modulus, 0]` for `modulus < 0` /// /// Panics if the exponent is negative or the modulus is zero. pub fn modpow(&self, exponent: &Self, modulus: &Self) -> Self { assert!( !exponent.is_negative(), "negative exponentiation is not supported!" ); assert!(!modulus.is_zero(), "divide by zero!"); let result = self.data.modpow(&exponent.data, &modulus.data); if result.is_zero() { return BigInt::zero(); } // The sign of the result follows the modulus, like `mod_floor`. let (sign, mag) = match (self.is_negative(), modulus.is_negative()) { (false, false) => (Plus, result), (true, false) => (Plus, &modulus.data - result), (false, true) => (Minus, &modulus.data - result), (true, true) => (Minus, result), }; BigInt::from_biguint(sign, mag) } /// Returns the truncated principal square root of `self` -- /// see [Roots::sqrt](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#method.sqrt). pub fn sqrt(&self) -> Self { Roots::sqrt(self) } /// Returns the truncated principal cube root of `self` -- /// see [Roots::cbrt](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#method.cbrt). pub fn cbrt(&self) -> Self { Roots::cbrt(self) } /// Returns the truncated principal `n`th root of `self` -- /// See [Roots::nth_root](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#tymethod.nth_root). pub fn nth_root(&self, n: u32) -> Self { Roots::nth_root(self, n) } pub fn get_limb(&self, n: usize) -> BigDigit { self.data.get_limb(n) } pub fn trailing_zeros(&self) -> Option { biguint::trailing_zeros(&self.data) } } impl_sum_iter_type!(BigInt); impl_product_iter_type!(BigInt); /// Perform in-place two's complement of the given binary representation, /// in little-endian byte order. #[inline] fn twos_complement_le(digits: &mut [u8]) { twos_complement(digits) } /// Perform in-place two's complement of the given binary representation /// in big-endian byte order. #[inline] fn twos_complement_be(digits: &mut [u8]) { twos_complement(digits.iter_mut().rev()) } /// Perform in-place two's complement of the given digit iterator /// starting from the least significant byte. #[inline] fn twos_complement<'a, I>(digits: I) where I: IntoIterator, { let mut carry = true; for d in digits { *d = d.not(); if carry { *d = d.wrapping_add(1); carry = d.is_zero(); } } } // Mod Inverse impl<'a> ModInverse<&'a BigUint> for BigInt { type Output = BigInt; fn mod_inverse(self, m: &'a BigUint) -> Option { if self.is_negative() { let v = self .mod_floor(&m.to_bigint().unwrap()) .into_biguint() .unwrap(); mod_inverse(Cow::Owned(v), Cow::Borrowed(m)) } else { mod_inverse(Cow::Owned(self.into_biguint().unwrap()), Cow::Borrowed(m)) } } } impl<'a> ModInverse<&'a BigInt> for BigInt { type Output = BigInt; fn mod_inverse(self, m: &'a BigInt) -> Option { if self.is_negative() { let v = self.mod_floor(m).into_biguint().unwrap(); mod_inverse(Cow::Owned(v), Cow::Owned(m.to_biguint().unwrap())) } else { mod_inverse( Cow::Owned(self.into_biguint().unwrap()), Cow::Owned(m.to_biguint().unwrap()), ) } } } impl<'a, 'b> ModInverse<&'b BigUint> for &'a BigInt { type Output = BigInt; fn mod_inverse(self, m: &'b BigUint) -> Option { if self.is_negative() { let v = self .mod_floor(&m.to_bigint().unwrap()) .into_biguint() .unwrap(); mod_inverse(Cow::Owned(v), Cow::Borrowed(m)) } else { mod_inverse(Cow::Owned(self.to_biguint().unwrap()), Cow::Borrowed(m)) } } } impl<'a, 'b> ModInverse<&'b BigInt> for &'a BigInt { type Output = BigInt; fn mod_inverse(self, m: &'b BigInt) -> Option { if self.is_negative() { let v = self.mod_floor(m).into_biguint().unwrap(); mod_inverse(Cow::Owned(v), Cow::Owned(m.to_biguint().unwrap())) } else { mod_inverse( Cow::Owned(self.to_biguint().unwrap()), Cow::Owned(m.to_biguint().unwrap()), ) } } } // Extended GCD impl<'a> ExtendedGcd<&'a BigUint> for BigInt { fn extended_gcd(self, other: &'a BigUint) -> (BigInt, BigInt, BigInt) { let (a, b, c) = extended_gcd( Cow::Owned(self.into_biguint().unwrap()), Cow::Borrowed(other), true, ); (a, b.unwrap(), c.unwrap()) } } impl<'a> ExtendedGcd<&'a BigInt> for BigInt { fn extended_gcd(self, other: &'a BigInt) -> (BigInt, BigInt, BigInt) { let (a, b, c) = extended_gcd( Cow::Owned(self.into_biguint().unwrap()), Cow::Owned(other.to_biguint().unwrap()), true, ); (a, b.unwrap(), c.unwrap()) } } impl<'a, 'b> ExtendedGcd<&'b BigInt> for &'a BigInt { fn extended_gcd(self, other: &'b BigInt) -> (BigInt, BigInt, BigInt) { let (a, b, c) = extended_gcd( Cow::Owned(self.to_biguint().unwrap()), Cow::Owned(other.to_biguint().unwrap()), true, ); (a, b.unwrap(), c.unwrap()) } } impl<'a, 'b> ExtendedGcd<&'b BigUint> for &'a BigInt { fn extended_gcd(self, other: &'b BigUint) -> (BigInt, BigInt, BigInt) { let (a, b, c) = extended_gcd( Cow::Owned(self.to_biguint().unwrap()), Cow::Borrowed(other), true, ); (a, b.unwrap(), c.unwrap()) } } // arbitrary support #[cfg(feature = "fuzz")] impl arbitrary::Arbitrary<'_> for BigInt { fn arbitrary(src: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result { let sign = if bool::arbitrary(src)? { Sign::Plus } else { Sign::Minus }; let data = BigUint::arbitrary(src)?; Ok(Self::from_biguint(sign, data)) } fn size_hint(depth: usize) -> (usize, Option) { arbitrary::size_hint::and(BigUint::size_hint(depth), bool::size_hint(depth)) } } #[test] fn test_from_biguint() { fn check(inp_s: Sign, inp_n: usize, ans_s: Sign, ans_n: usize) { let inp = BigInt::from_biguint(inp_s, FromPrimitive::from_usize(inp_n).unwrap()); let ans = BigInt { sign: ans_s, data: FromPrimitive::from_usize(ans_n).unwrap(), }; assert_eq!(inp, ans); } check(Plus, 1, Plus, 1); check(Plus, 0, NoSign, 0); check(Minus, 1, Minus, 1); check(NoSign, 1, NoSign, 0); } #[test] fn test_from_slice() { fn check(inp_s: Sign, inp_n: u32, ans_s: Sign, ans_n: u32) { let inp = BigInt::from_slice(inp_s, &[inp_n]); let ans = BigInt { sign: ans_s, data: FromPrimitive::from_u32(ans_n).unwrap(), }; assert_eq!(inp, ans); } check(Plus, 1, Plus, 1); check(Plus, 0, NoSign, 0); check(Minus, 1, Minus, 1); check(NoSign, 1, NoSign, 0); } #[test] fn test_assign_from_slice() { fn check(inp_s: Sign, inp_n: u32, ans_s: Sign, ans_n: u32) { let mut inp = BigInt::from_slice(Minus, &[2627_u32, 0_u32, 9182_u32, 42_u32]); inp.assign_from_slice(inp_s, &[inp_n]); let ans = BigInt { sign: ans_s, data: FromPrimitive::from_u32(ans_n).unwrap(), }; assert_eq!(inp, ans); } check(Plus, 1, Plus, 1); check(Plus, 0, NoSign, 0); check(Minus, 1, Minus, 1); check(NoSign, 1, NoSign, 0); } #[test] fn test_bigint_negate() { let mut a = BigInt { sign: Plus, data: FromPrimitive::from_usize(1).unwrap(), }; negate_sign(&mut a); assert_eq!(a.sign, Minus); // fn check(inp_s: Sign, inp_n: usize, ans_s: Sign, ans_n: usize) { // let inp = BigInt::from_biguint(inp_s, FromPrimitive::from_usize(inp_n).unwrap()); // let ans = // } // check(Plus, 1, Plus, 1); // check(Plus, 0, NoSign, 0); // check(Minus, 1, Minus, 1); // check(NoSign, 1, NoSign, 0); } num-bigint-dig-0.8.2/src/bigrand.rs000064400000000000000000000260401046102023000152120ustar 00000000000000//! Randomization of big integers use rand::distributions::uniform::{SampleBorrow, SampleUniform, UniformSampler}; use rand::prelude::*; use rand::Rng; use crate::BigInt; use crate::BigUint; use crate::Sign::*; use crate::big_digit::BigDigit; use crate::bigint::{into_magnitude, magnitude}; use crate::integer::Integer; #[cfg(feature = "prime")] use num_iter::range_step; use num_traits::Zero; #[cfg(feature = "prime")] use num_traits::{FromPrimitive, ToPrimitive}; #[cfg(feature = "prime")] use crate::prime::probably_prime; pub trait RandBigInt { /// Generate a random `BigUint` of the given bit size. fn gen_biguint(&mut self, bit_size: usize) -> BigUint; /// Generate a random BigInt of the given bit size. fn gen_bigint(&mut self, bit_size: usize) -> BigInt; /// Generate a random `BigUint` less than the given bound. Fails /// when the bound is zero. fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint; /// Generate a random `BigUint` within the given range. The lower /// bound is inclusive; the upper bound is exclusive. Fails when /// the upper bound is not greater than the lower bound. fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint; /// Generate a random `BigInt` within the given range. The lower /// bound is inclusive; the upper bound is exclusive. Fails when /// the upper bound is not greater than the lower bound. fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt; } impl RandBigInt for R { fn gen_biguint(&mut self, bit_size: usize) -> BigUint { use super::big_digit::BITS; let (digits, rem) = bit_size.div_rem(&BITS); let mut data = smallvec![BigDigit::default(); digits + (rem > 0) as usize]; // `fill` is faster than many `gen::` calls // Internally this calls `SeedableRng` where implementors are responsible for adjusting endianness for reproducable values. self.fill(data.as_mut_slice()); if rem > 0 { data[digits] >>= BITS - rem; } BigUint::new_native(data) } fn gen_bigint(&mut self, bit_size: usize) -> BigInt { loop { // Generate a random BigUint... let biguint = self.gen_biguint(bit_size); // ...and then randomly assign it a Sign... let sign = if biguint.is_zero() { // ...except that if the BigUint is zero, we need to try // again with probability 0.5. This is because otherwise, // the probability of generating a zero BigInt would be // double that of any other number. if self.gen() { continue; } else { NoSign } } else if self.gen() { Plus } else { Minus }; return BigInt::from_biguint(sign, biguint); } } fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint { assert!(!bound.is_zero()); let bits = bound.bits(); loop { let n = self.gen_biguint(bits); if n < *bound { return n; } } } fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint { assert!(*lbound < *ubound); if lbound.is_zero() { self.gen_biguint_below(ubound) } else { lbound + self.gen_biguint_below(&(ubound - lbound)) } } fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt { assert!(*lbound < *ubound); if lbound.is_zero() { BigInt::from(self.gen_biguint_below(magnitude(&ubound))) } else if ubound.is_zero() { lbound + BigInt::from(self.gen_biguint_below(magnitude(&lbound))) } else { let delta = ubound - lbound; lbound + BigInt::from(self.gen_biguint_below(magnitude(&delta))) } } } /// The back-end implementing rand's `UniformSampler` for `BigUint`. #[derive(Clone, Debug)] pub struct UniformBigUint { base: BigUint, len: BigUint, } impl UniformSampler for UniformBigUint { type X = BigUint; #[inline] fn new(low_b: B1, high_b: B2) -> Self where B1: SampleBorrow + Sized, B2: SampleBorrow + Sized, { let low = low_b.borrow(); let high = high_b.borrow(); assert!(low < high); UniformBigUint { len: high - low, base: low.clone(), } } #[inline] fn new_inclusive(low_b: B1, high_b: B2) -> Self where B1: SampleBorrow + Sized, B2: SampleBorrow + Sized, { Self::new(low_b, high_b.borrow() + 1u32) } #[inline] fn sample(&self, rng: &mut R) -> Self::X { &self.base + rng.gen_biguint_below(&self.len) } #[inline] fn sample_single(low_b: B1, high_b: B2, rng: &mut R) -> Self::X where B1: SampleBorrow + Sized, B2: SampleBorrow + Sized, { let low = low_b.borrow(); let high = high_b.borrow(); rng.gen_biguint_range(low, high) } } impl SampleUniform for BigUint { type Sampler = UniformBigUint; } /// The back-end implementing rand's `UniformSampler` for `BigInt`. #[derive(Clone, Debug)] pub struct UniformBigInt { base: BigInt, len: BigUint, } impl UniformSampler for UniformBigInt { type X = BigInt; #[inline] fn new(low_b: B1, high_b: B2) -> Self where B1: SampleBorrow + Sized, B2: SampleBorrow + Sized, { let low = low_b.borrow(); let high = high_b.borrow(); assert!(low < high); UniformBigInt { len: into_magnitude(high - low), base: low.clone(), } } #[inline] fn new_inclusive(low_b: B1, high_b: B2) -> Self where B1: SampleBorrow + Sized, B2: SampleBorrow + Sized, { let low = low_b.borrow(); let high = high_b.borrow(); assert!(low <= high); Self::new(low, high + 1u32) } #[inline] fn sample(&self, rng: &mut R) -> Self::X { &self.base + BigInt::from(rng.gen_biguint_below(&self.len)) } #[inline] fn sample_single(low_b: B1, high_b: B2, rng: &mut R) -> Self::X where B1: SampleBorrow + Sized, B2: SampleBorrow + Sized, { let low = low_b.borrow(); let high = high_b.borrow(); rng.gen_bigint_range(low, high) } } impl SampleUniform for BigInt { type Sampler = UniformBigInt; } /// A random distribution for `BigUint` and `BigInt` values of a particular bit size. #[derive(Clone, Copy, Debug)] pub struct RandomBits { bits: usize, } impl RandomBits { #[inline] pub fn new(bits: usize) -> RandomBits { RandomBits { bits } } } impl Distribution for RandomBits { #[inline] fn sample(&self, rng: &mut R) -> BigUint { rng.gen_biguint(self.bits) } } impl Distribution for RandomBits { #[inline] fn sample(&self, rng: &mut R) -> BigInt { rng.gen_bigint(self.bits) } } /// A generic trait for generating random primes. /// /// *Warning*: This is highly dependend on the provided random number generator, /// to provide actually random primes. /// /// # Example #[cfg_attr(feature = "std", doc = " ```")] #[cfg_attr(not(feature = "std"), doc = " ```ignore")] /// extern crate rand; /// extern crate num_bigint_dig as num_bigint; /// /// use rand::thread_rng; /// use num_bigint::RandPrime; /// /// let mut rng = thread_rng(); /// let p = rng.gen_prime(1024); /// assert_eq!(p.bits(), 1024); /// ``` /// #[cfg(feature = "prime")] pub trait RandPrime { /// Generate a random prime number with as many bits as given. fn gen_prime(&mut self, bits: usize) -> BigUint; } /// A list of small, prime numbers that allows us to rapidly /// exclude some fraction of composite candidates when searching for a random /// prime. This list is truncated at the point where smallPrimesProduct exceeds /// a u64. It does not include two because we ensure that the candidates are /// odd by construction. #[cfg(feature = "prime")] const SMALL_PRIMES: [u8; 15] = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53]; #[cfg(feature = "prime")] lazy_static! { /// The product of the values in SMALL_PRIMES and allows us /// to reduce a candidate prime by this number and then determine whether it's /// coprime to all the elements of SMALL_PRIMES without further BigUint /// operations. static ref SMALL_PRIMES_PRODUCT: BigUint = BigUint::from_u64(16_294_579_238_595_022_365).unwrap(); } #[cfg(feature = "prime")] impl RandPrime for R { fn gen_prime(&mut self, bit_size: usize) -> BigUint { if bit_size < 2 { panic!("prime size must be at least 2-bit"); } let mut b = bit_size % 8; if b == 0 { b = 8; } let bytes_len = (bit_size + 7) / 8; let mut bytes = vec![0u8; bytes_len]; loop { self.fill_bytes(&mut bytes); // Clear bits in the first byte to make sure the candidate has a size <= bits. bytes[0] &= ((1u32 << (b as u32)) - 1) as u8; // Don't let the value be too small, i.e, set the most significant two bits. // Setting the top two bits, rather than just the top bit, // means that when two of these values are multiplied together, // the result isn't ever one bit short. if b >= 2 { bytes[0] |= 3u8.wrapping_shl(b as u32 - 2); } else { // Here b==1, because b cannot be zero. bytes[0] |= 1; if bytes_len > 1 { bytes[1] |= 0x80; } } // Make the value odd since an even number this large certainly isn't prime. bytes[bytes_len - 1] |= 1u8; let mut p = BigUint::from_bytes_be(&bytes); // must always be a u64, as the SMALL_PRIMES_PRODUCT is a u64 let rem = (&p % &*SMALL_PRIMES_PRODUCT).to_u64().unwrap(); 'next: for delta in range_step(0, 1 << 20, 2) { let m = rem + delta; for prime in &SMALL_PRIMES { if m % u64::from(*prime) == 0 && (bit_size > 6 || m != u64::from(*prime)) { continue 'next; } } if delta > 0 { p += BigUint::from_u64(delta).unwrap(); } break; } // There is a tiny possibility that, by adding delta, we caused // the number to be one bit too long. Thus we check bit length here. if p.bits() == bit_size && probably_prime(&p, 20) { return p; } } } } num-bigint-dig-0.8.2/src/biguint.rs000064400000000000000000003100361046102023000152460ustar 00000000000000#[allow(deprecated, unused_imports)] use alloc::borrow::Cow; use alloc::string::String; use alloc::vec::Vec; use core::cmp::Ordering::{self, Equal, Greater, Less}; use core::default::Default; use core::hash::{Hash, Hasher}; use core::iter::{Product, Sum}; use core::ops::{ Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign, }; use core::str::{self, FromStr}; use core::{cmp, fmt, mem}; use core::{f32, f64}; use core::{u32, u64, u8}; #[cfg(feature = "serde")] use serde; #[cfg(feature = "zeroize")] use zeroize::Zeroize; #[cfg(feature = "std")] fn sqrt(a: f64) -> f64 { a.sqrt() } #[cfg(not(feature = "std"))] fn sqrt(a: f64) -> f64 { libm::sqrt(a) } #[cfg(feature = "std")] fn ln(a: f64) -> f64 { a.ln() } #[cfg(not(feature = "std"))] fn ln(a: f64) -> f64 { libm::log(a) } #[cfg(feature = "std")] fn cbrt(a: f64) -> f64 { a.cbrt() } #[cfg(not(feature = "std"))] fn cbrt(a: f64) -> f64 { libm::cbrt(a) } #[cfg(feature = "std")] fn exp(a: f64) -> f64 { a.exp() } #[cfg(not(feature = "std"))] fn exp(a: f64) -> f64 { libm::exp(a) } use crate::integer::{Integer, Roots}; use num_traits::float::FloatCore; use num_traits::{ CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, FromPrimitive, Num, One, Pow, ToPrimitive, Unsigned, Zero, }; use crate::BigInt; use crate::big_digit::{self, BigDigit}; use smallvec::SmallVec; #[path = "monty.rs"] mod monty; use self::monty::monty_modpow; use super::VEC_SIZE; use crate::algorithms::{__add2, __sub2rev, add2, sub2, sub2rev}; use crate::algorithms::{biguint_shl, biguint_shr}; use crate::algorithms::{cmp_slice, fls, idiv_ceil, ilog2}; use crate::algorithms::{div_rem, div_rem_digit, mac_with_carry, mul3, scalar_mul}; use crate::algorithms::{extended_gcd, mod_inverse}; use crate::traits::{ExtendedGcd, ModInverse}; use crate::ParseBigIntError; use crate::UsizePromotion; /// A big unsigned integer type. #[derive(Clone, Debug)] pub struct BigUint { pub(crate) data: SmallVec<[BigDigit; VEC_SIZE]>, } impl PartialEq for BigUint { #[inline] fn eq(&self, other: &BigUint) -> bool { match self.cmp(other) { Equal => true, _ => false, } } } impl Eq for BigUint {} impl Hash for BigUint { fn hash(&self, state: &mut H) { self.data.hash(state); } } impl PartialOrd for BigUint { #[inline] fn partial_cmp(&self, other: &BigUint) -> Option { Some(self.cmp(other)) } } impl Ord for BigUint { #[inline] fn cmp(&self, other: &BigUint) -> Ordering { cmp_slice(&self.data[..], &other.data[..]) } } impl Default for BigUint { #[inline] fn default() -> BigUint { Zero::zero() } } #[cfg(feature = "zeroize")] impl Zeroize for BigUint { fn zeroize(&mut self) { self.data.as_mut().zeroize(); } } impl fmt::Display for BigUint { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad_integral(true, "", &self.to_str_radix(10)) } } impl fmt::LowerHex for BigUint { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad_integral(true, "0x", &self.to_str_radix(16)) } } impl fmt::UpperHex for BigUint { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut s = self.to_str_radix(16); s.make_ascii_uppercase(); f.pad_integral(true, "0x", &s) } } impl fmt::Binary for BigUint { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad_integral(true, "0b", &self.to_str_radix(2)) } } impl fmt::Octal for BigUint { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad_integral(true, "0o", &self.to_str_radix(8)) } } impl FromStr for BigUint { type Err = ParseBigIntError; #[inline] fn from_str(s: &str) -> Result { BigUint::from_str_radix(s, 10) } } // Convert from a power of two radix (bits == ilog2(radix)) where bits evenly divides // BigDigit::BITS fn from_bitwise_digits_le(v: &[u8], bits: usize) -> BigUint { debug_assert!(!v.is_empty() && bits <= 8 && big_digit::BITS % bits == 0); debug_assert!(v.iter().all(|&c| (c as BigDigit) < (1 << bits))); let digits_per_big_digit = big_digit::BITS / bits; let data = v .chunks(digits_per_big_digit) .map(|chunk| { chunk .iter() .rev() .fold(0, |acc, &c| (acc << bits) | c as BigDigit) }) .collect(); BigUint::new_native(data) } // Convert from a power of two radix (bits == ilog2(radix)) where bits doesn't evenly divide // BigDigit::BITS fn from_inexact_bitwise_digits_le(v: &[u8], bits: usize) -> BigUint { debug_assert!(!v.is_empty() && bits <= 8 && big_digit::BITS % bits != 0); debug_assert!(v.iter().all(|&c| (c as BigDigit) < (1 << bits))); let big_digits = (v.len() * bits + big_digit::BITS - 1) / big_digit::BITS; let mut data = SmallVec::with_capacity(big_digits); let mut d = 0; let mut dbits = 0; // number of bits we currently have in d // walk v accumululating bits in d; whenever we accumulate big_digit::BITS in d, spit out a // big_digit: for &c in v { d |= (c as BigDigit) << dbits; dbits += bits; if dbits >= big_digit::BITS { data.push(d); dbits -= big_digit::BITS; // if dbits was > big_digit::BITS, we dropped some of the bits in c (they couldn't fit // in d) - grab the bits we lost here: d = (c as BigDigit) >> (bits - dbits); } } if dbits > 0 { debug_assert!(dbits < big_digit::BITS); data.push(d as BigDigit); } BigUint::new_native(data) } // Read little-endian radix digits fn from_radix_digits_be(v: &[u8], radix: u32) -> BigUint { debug_assert!(!v.is_empty() && !radix.is_power_of_two()); debug_assert!(v.iter().all(|&c| (c as u32) < radix)); // Estimate how big the result will be, so we can pre-allocate it. let bits = ilog2(radix) * v.len(); let big_digits = idiv_ceil(bits, big_digit::BITS); let mut data = SmallVec::with_capacity(big_digits); let (base, power) = get_radix_base(radix); let radix = radix as BigDigit; let r = v.len() % power; let i = if r == 0 { power } else { r }; let (head, tail) = v.split_at(i); let first = head.iter().fold(0, |acc, &d| acc * radix + d as BigDigit); data.push(first); debug_assert!(tail.len() % power == 0); for chunk in tail.chunks(power) { if data.last() != Some(&0) { data.push(0); } let mut carry = 0; for d in data.iter_mut() { *d = mac_with_carry(0, *d, base, &mut carry); } debug_assert!(carry == 0); let n = chunk.iter().fold(0, |acc, &d| acc * radix + d as BigDigit); add2(&mut data, &[n]); } BigUint::new_native(data) } impl Num for BigUint { type FromStrRadixErr = ParseBigIntError; /// Creates and initializes a `BigUint`. fn from_str_radix(s: &str, radix: u32) -> Result { assert!(2 <= radix && radix <= 36, "The radix must be within 2...36"); let mut s = s; if s.starts_with('+') { let tail = &s[1..]; if !tail.starts_with('+') { s = tail } } if s.is_empty() { return Err(ParseBigIntError::empty()); } if s.starts_with('_') { // Must lead with a real digit! return Err(ParseBigIntError::invalid()); } // First normalize all characters to plain digit values let mut v = Vec::with_capacity(s.len()); for b in s.bytes() { let d = match b { b'0'..=b'9' => b - b'0', b'a'..=b'z' => b - b'a' + 10, b'A'..=b'Z' => b - b'A' + 10, b'_' => continue, _ => u8::MAX, }; if d < radix as u8 { v.push(d); } else { return Err(ParseBigIntError::invalid()); } } let res = if radix.is_power_of_two() { // Powers of two can use bitwise masks and shifting instead of multiplication let bits = ilog2(radix); v.reverse(); if big_digit::BITS % bits == 0 { from_bitwise_digits_le(&v, bits) } else { from_inexact_bitwise_digits_le(&v, bits) } } else { from_radix_digits_be(&v, radix) }; Ok(res) } } forward_val_val_binop!(impl BitAnd for BigUint, bitand); forward_ref_val_binop!(impl BitAnd for BigUint, bitand); // do not use forward_ref_ref_binop_commutative! for bitand so that we can // clone the smaller value rather than the larger, avoiding over-allocation impl<'a, 'b> BitAnd<&'b BigUint> for &'a BigUint { type Output = BigUint; #[inline] fn bitand(self, other: &BigUint) -> BigUint { // forward to val-ref, choosing the smaller to clone if self.data.len() <= other.data.len() { self.clone() & other } else { other.clone() & self } } } forward_val_assign!(impl BitAndAssign for BigUint, bitand_assign); impl<'a> BitAnd<&'a BigUint> for BigUint { type Output = BigUint; #[inline] fn bitand(mut self, other: &BigUint) -> BigUint { self &= other; self } } impl<'a> BitAndAssign<&'a BigUint> for BigUint { #[inline] fn bitand_assign(&mut self, other: &BigUint) { for (ai, &bi) in self.data.iter_mut().zip(other.data.iter()) { *ai &= bi; } self.data.truncate(other.data.len()); self.normalize(); } } forward_all_binop_to_val_ref_commutative!(impl BitOr for BigUint, bitor); forward_val_assign!(impl BitOrAssign for BigUint, bitor_assign); impl<'a> BitOr<&'a BigUint> for BigUint { type Output = BigUint; fn bitor(mut self, other: &BigUint) -> BigUint { self |= other; self } } impl<'a> BitOrAssign<&'a BigUint> for BigUint { #[inline] fn bitor_assign(&mut self, other: &BigUint) { for (ai, &bi) in self.data.iter_mut().zip(other.data.iter()) { *ai |= bi; } if other.data.len() > self.data.len() { let extra = &other.data[self.data.len()..]; self.data.extend(extra.iter().cloned()); } } } forward_all_binop_to_val_ref_commutative!(impl BitXor for BigUint, bitxor); forward_val_assign!(impl BitXorAssign for BigUint, bitxor_assign); impl<'a> BitXor<&'a BigUint> for BigUint { type Output = BigUint; fn bitxor(mut self, other: &BigUint) -> BigUint { self ^= other; self } } impl<'a> BitXorAssign<&'a BigUint> for BigUint { #[inline] fn bitxor_assign(&mut self, other: &BigUint) { for (ai, &bi) in self.data.iter_mut().zip(other.data.iter()) { *ai ^= bi; } if other.data.len() > self.data.len() { let extra = &other.data[self.data.len()..]; self.data.extend(extra.iter().cloned()); } self.normalize(); } } impl Shl for BigUint { type Output = BigUint; #[inline] fn shl(self, rhs: usize) -> BigUint { biguint_shl(Cow::Owned(self), rhs) } } impl<'a> Shl for &'a BigUint { type Output = BigUint; #[inline] fn shl(self, rhs: usize) -> BigUint { biguint_shl(Cow::Borrowed(self), rhs) } } impl ShlAssign for BigUint { #[inline] fn shl_assign(&mut self, rhs: usize) { let n = mem::replace(self, BigUint::zero()); *self = n << rhs; } } impl Shr for BigUint { type Output = BigUint; #[inline] fn shr(self, rhs: usize) -> BigUint { biguint_shr(Cow::Owned(self), rhs) } } impl<'a> Shr for &'a BigUint { type Output = BigUint; #[inline] fn shr(self, rhs: usize) -> BigUint { biguint_shr(Cow::Borrowed(self), rhs) } } impl ShrAssign for BigUint { #[inline] fn shr_assign(&mut self, rhs: usize) { let n = mem::replace(self, BigUint::zero()); *self = n >> rhs; } } impl Zero for BigUint { #[inline] fn zero() -> BigUint { BigUint::new(Vec::new()) } #[inline] fn is_zero(&self) -> bool { self.data.is_empty() } } impl One for BigUint { #[inline] fn one() -> BigUint { BigUint::new(vec![1]) } #[inline] fn is_one(&self) -> bool { self.data[..] == [1] } } impl Unsigned for BigUint {} macro_rules! pow_impl { ($T:ty) => { impl<'a> Pow<$T> for &'a BigUint { type Output = BigUint; #[inline] fn pow(self, mut exp: $T) -> Self::Output { if exp == 0 { return BigUint::one(); } let mut base = self.clone(); while exp & 1 == 0 { base = &base * &base; exp >>= 1; } if exp == 1 { return base; } let mut acc = base.clone(); while exp > 1 { exp >>= 1; base = &base * &base; if exp & 1 == 1 { acc = &acc * &base; } } acc } } impl<'a, 'b> Pow<&'b $T> for &'a BigUint { type Output = BigUint; #[inline] fn pow(self, exp: &$T) -> Self::Output { self.pow(*exp) } } }; } pow_impl!(u8); pow_impl!(u16); pow_impl!(u32); pow_impl!(u64); pow_impl!(usize); #[cfg(has_i128)] pow_impl!(u128); forward_all_binop_to_val_ref_commutative!(impl Add for BigUint, add); forward_val_assign!(impl AddAssign for BigUint, add_assign); impl<'a> Add<&'a BigUint> for BigUint { type Output = BigUint; fn add(mut self, other: &BigUint) -> BigUint { self += other; self } } impl<'a> AddAssign<&'a BigUint> for BigUint { #[inline] fn add_assign(&mut self, other: &BigUint) { let self_len = self.data.len(); let carry = if self_len < other.data.len() { let lo_carry = __add2(&mut self.data[..], &other.data[..self_len]); self.data.extend_from_slice(&other.data[self_len..]); __add2(&mut self.data[self_len..], &[lo_carry]) } else { __add2(&mut self.data[..], &other.data[..]) }; if carry != 0 { self.data.push(carry); } } } promote_unsigned_scalars!(impl Add for BigUint, add); promote_unsigned_scalars_assign!(impl AddAssign for BigUint, add_assign); forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigUint, add); forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigUint, add); #[cfg(has_i128)] forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigUint, add); impl Add for BigUint { type Output = BigUint; #[inline] fn add(mut self, other: u32) -> BigUint { self += other; self } } impl AddAssign for BigUint { #[inline] fn add_assign(&mut self, other: u32) { if other != 0 { if self.data.len() == 0 { self.data.push(0); } let carry = __add2(&mut self.data, &[other as BigDigit]); if carry != 0 { self.data.push(carry); } } } } impl Add for BigUint { type Output = BigUint; #[inline] fn add(mut self, other: u64) -> BigUint { self += other; self } } impl AddAssign for BigUint { #[cfg(not(feature = "u64_digit"))] #[inline] fn add_assign(&mut self, other: u64) { let (hi, lo) = big_digit::from_doublebigdigit(other); if hi == 0 { *self += lo; } else { while self.data.len() < 2 { self.data.push(0); } let carry = __add2(&mut self.data, &[lo, hi]); if carry != 0 { self.data.push(carry); } } } #[cfg(feature = "u64_digit")] #[inline] fn add_assign(&mut self, other: u64) { if other != 0 { if self.data.len() == 0 { self.data.push(0); } let carry = __add2(&mut self.data, &[other as BigDigit]); if carry != 0 { self.data.push(carry); } } } } #[cfg(has_i128)] impl Add for BigUint { type Output = BigUint; #[inline] fn add(mut self, other: u128) -> BigUint { self += other; self } } #[cfg(has_i128)] impl AddAssign for BigUint { #[cfg(not(feature = "u64_digit"))] #[inline] fn add_assign(&mut self, other: u128) { if other <= u64::max_value() as u128 { *self += other as u64 } else { let (a, b, c, d) = u32_from_u128(other); let carry = if a > 0 { while self.data.len() < 4 { self.data.push(0); } __add2(&mut self.data, &[d, c, b, a]) } else { debug_assert!(b > 0); while self.data.len() < 3 { self.data.push(0); } __add2(&mut self.data, &[d, c, b]) }; if carry != 0 { self.data.push(carry); } } } #[cfg(feature = "u64_digit")] #[inline] fn add_assign(&mut self, other: u128) { let (hi, lo) = big_digit::from_doublebigdigit(other); if hi == 0 { *self += lo; } else { while self.data.len() < 2 { self.data.push(0); } let carry = __add2(&mut self.data, &[lo, hi]); if carry != 0 { self.data.push(carry); } } } } forward_val_val_binop!(impl Sub for BigUint, sub); forward_ref_ref_binop!(impl Sub for BigUint, sub); forward_val_assign!(impl SubAssign for BigUint, sub_assign); impl<'a> Sub<&'a BigUint> for BigUint { type Output = BigUint; fn sub(mut self, other: &BigUint) -> BigUint { self -= other; self } } impl<'a> SubAssign<&'a BigUint> for BigUint { fn sub_assign(&mut self, other: &'a BigUint) { sub2(&mut self.data[..], &other.data[..]); self.normalize(); } } impl<'a> Sub for &'a BigUint { type Output = BigUint; fn sub(self, mut other: BigUint) -> BigUint { let other_len = other.data.len(); if other_len < self.data.len() { let lo_borrow = __sub2rev(&self.data[..other_len], &mut other.data); other.data.extend_from_slice(&self.data[other_len..]); if lo_borrow != 0 { sub2(&mut other.data[other_len..], &[1]) } } else { sub2rev(&self.data[..], &mut other.data[..]); } other.normalized() } } promote_unsigned_scalars!(impl Sub for BigUint, sub); promote_unsigned_scalars_assign!(impl SubAssign for BigUint, sub_assign); forward_all_scalar_binop_to_val_val!(impl Sub for BigUint, sub); forward_all_scalar_binop_to_val_val!(impl Sub for BigUint, sub); #[cfg(has_i128)] forward_all_scalar_binop_to_val_val!(impl Sub for BigUint, sub); impl Sub for BigUint { type Output = BigUint; #[inline] fn sub(mut self, other: u32) -> BigUint { self -= other; self } } impl SubAssign for BigUint { fn sub_assign(&mut self, other: u32) { sub2(&mut self.data[..], &[other as BigDigit]); self.normalize(); } } impl Sub for u32 { type Output = BigUint; #[cfg(not(feature = "u64_digit"))] #[inline] fn sub(self, mut other: BigUint) -> BigUint { if other.data.len() == 0 { other.data.push(self); } else { sub2rev(&[self], &mut other.data[..]); } other.normalized() } #[cfg(feature = "u64_digit")] #[inline] fn sub(self, mut other: BigUint) -> BigUint { if other.data.len() == 0 { other.data.push(self as BigDigit); } else { sub2rev(&[self as BigDigit], &mut other.data[..]); } other.normalized() } } impl Sub for BigUint { type Output = BigUint; #[inline] fn sub(mut self, other: u64) -> BigUint { self -= other; self } } impl SubAssign for BigUint { #[cfg(not(feature = "u64_digit"))] #[inline] fn sub_assign(&mut self, other: u64) { let (hi, lo) = big_digit::from_doublebigdigit(other); sub2(&mut self.data[..], &[lo, hi]); self.normalize(); } #[cfg(feature = "u64_digit")] #[inline] fn sub_assign(&mut self, other: u64) { sub2(&mut self.data[..], &[other as BigDigit]); self.normalize(); } } impl Sub for u64 { type Output = BigUint; #[cfg(not(feature = "u64_digit"))] #[inline] fn sub(self, mut other: BigUint) -> BigUint { while other.data.len() < 2 { other.data.push(0); } let (hi, lo) = big_digit::from_doublebigdigit(self); sub2rev(&[lo, hi], &mut other.data[..]); other.normalized() } #[cfg(feature = "u64_digit")] #[inline] fn sub(self, mut other: BigUint) -> BigUint { if other.data.len() == 0 { other.data.push(self); } else { sub2rev(&[self], &mut other.data[..]); } other.normalized() } } #[cfg(has_i128)] impl Sub for BigUint { type Output = BigUint; #[inline] fn sub(mut self, other: u128) -> BigUint { self -= other; self } } #[cfg(has_i128)] impl SubAssign for BigUint { #[cfg(not(feature = "u64_digit"))] #[inline] fn sub_assign(&mut self, other: u128) { let (a, b, c, d) = u32_from_u128(other); sub2(&mut self.data[..], &[d, c, b, a]); self.normalize(); } #[cfg(feature = "u64_digit")] #[inline] fn sub_assign(&mut self, other: u128) { let (hi, lo) = big_digit::from_doublebigdigit(other); sub2(&mut self.data[..], &[lo, hi]); self.normalize(); } } #[cfg(has_i128)] impl Sub for u128 { type Output = BigUint; #[cfg(not(feature = "u64_digit"))] #[inline] fn sub(self, mut other: BigUint) -> BigUint { while other.data.len() < 4 { other.data.push(0); } let (a, b, c, d) = u32_from_u128(self); sub2rev(&[d, c, b, a], &mut other.data[..]); other.normalized() } #[cfg(feature = "u64_digit")] #[inline] fn sub(self, mut other: BigUint) -> BigUint { while other.data.len() < 2 { other.data.push(0); } let (hi, lo) = big_digit::from_doublebigdigit(self); sub2rev(&[lo, hi], &mut other.data[..]); other.normalized() } } forward_all_binop_to_ref_ref!(impl Mul for BigUint, mul); forward_val_assign!(impl MulAssign for BigUint, mul_assign); impl<'a, 'b> Mul<&'b BigUint> for &'a BigUint { type Output = BigUint; #[inline] fn mul(self, other: &BigUint) -> BigUint { mul3(&self.data[..], &other.data[..]) } } impl<'a, 'b> Mul<&'a BigInt> for &'b BigUint { type Output = BigInt; #[inline] fn mul(self, other: &BigInt) -> BigInt { BigInt { data: mul3(&self.data[..], &other.digits()[..]), sign: other.sign, } } } impl<'a> MulAssign<&'a BigUint> for BigUint { #[inline] fn mul_assign(&mut self, other: &'a BigUint) { *self = &*self * other } } promote_unsigned_scalars!(impl Mul for BigUint, mul); promote_unsigned_scalars_assign!(impl MulAssign for BigUint, mul_assign); forward_all_scalar_binop_to_val_val_commutative!(impl Mul for BigUint, mul); forward_all_scalar_binop_to_val_val_commutative!(impl Mul for BigUint, mul); #[cfg(has_i128)] forward_all_scalar_binop_to_val_val_commutative!(impl Mul for BigUint, mul); impl Mul for BigUint { type Output = BigUint; #[inline] fn mul(mut self, other: u32) -> BigUint { self *= other; self } } impl MulAssign for BigUint { #[inline] fn mul_assign(&mut self, other: u32) { if other == 0 { self.data.clear(); } else { let carry = scalar_mul(&mut self.data[..], other as BigDigit); if carry != 0 { self.data.push(carry); } } } } impl Mul for BigUint { type Output = BigUint; #[inline] fn mul(mut self, other: u64) -> BigUint { self *= other; self } } impl MulAssign for BigUint { #[cfg(not(feature = "u64_digit"))] #[inline] fn mul_assign(&mut self, other: u64) { if other == 0 { self.data.clear(); } else if other <= BigDigit::max_value() as u64 { *self *= other as BigDigit } else { let (hi, lo) = big_digit::from_doublebigdigit(other); *self = mul3(&self.data[..], &[lo, hi]) } } #[cfg(feature = "u64_digit")] #[inline] fn mul_assign(&mut self, other: u64) { if other == 0 { self.data.clear(); } else { let carry = scalar_mul(&mut self.data[..], other as BigDigit); if carry != 0 { self.data.push(carry); } } } } #[cfg(has_i128)] impl Mul for BigUint { type Output = BigUint; #[inline] fn mul(mut self, other: u128) -> BigUint { self *= other; self } } #[cfg(has_i128)] impl MulAssign for BigUint { #[cfg(not(feature = "u64_digit"))] #[inline] fn mul_assign(&mut self, other: u128) { if other == 0 { self.data.clear(); } else if other <= BigDigit::max_value() as u128 { *self *= other as BigDigit } else { let (a, b, c, d) = u32_from_u128(other); *self = mul3(&self.data[..], &[d, c, b, a]) } } #[cfg(feature = "u64_digit")] #[inline] fn mul_assign(&mut self, other: u128) { if other == 0 { self.data.clear(); } else if other <= BigDigit::max_value() as u128 { *self *= other as BigDigit } else { let (hi, lo) = big_digit::from_doublebigdigit(other); *self = mul3(&self.data[..], &[lo, hi]) } } } forward_all_binop_to_ref_ref!(impl Div for BigUint, div); forward_val_assign!(impl DivAssign for BigUint, div_assign); impl<'a, 'b> Div<&'b BigUint> for &'a BigUint { type Output = BigUint; #[inline] fn div(self, other: &BigUint) -> BigUint { let (q, _) = self.div_rem(other); q } } impl<'a> DivAssign<&'a BigUint> for BigUint { #[inline] fn div_assign(&mut self, other: &'a BigUint) { *self = &*self / other; } } promote_unsigned_scalars!(impl Div for BigUint, div); promote_unsigned_scalars_assign!(impl DivAssign for BigUint, div_assign); forward_all_scalar_binop_to_val_val!(impl Div for BigUint, div); forward_all_scalar_binop_to_val_val!(impl Div for BigUint, div); #[cfg(has_i128)] forward_all_scalar_binop_to_val_val!(impl Div for BigUint, div); impl Div for BigUint { type Output = BigUint; #[inline] fn div(self, other: u32) -> BigUint { let (q, _) = div_rem_digit(self, other as BigDigit); q } } impl DivAssign for BigUint { #[inline] fn div_assign(&mut self, other: u32) { *self = &*self / other; } } impl Div for u32 { type Output = BigUint; #[inline] fn div(self, other: BigUint) -> BigUint { match other.data.len() { 0 => panic!(), 1 => From::from(self as BigDigit / other.data[0]), _ => Zero::zero(), } } } impl Div for BigUint { type Output = BigUint; #[inline] fn div(self, other: u64) -> BigUint { let (q, _) = self.div_rem(&From::from(other)); q } } impl DivAssign for BigUint { #[inline] fn div_assign(&mut self, other: u64) { *self = &*self / other; } } impl Div for u64 { type Output = BigUint; #[cfg(not(feature = "u64_digit"))] #[inline] fn div(self, other: BigUint) -> BigUint { match other.data.len() { 0 => panic!(), 1 => From::from(self / other.data[0] as u64), 2 => From::from(self / big_digit::to_doublebigdigit(other.data[1], other.data[0])), _ => Zero::zero(), } } #[cfg(feature = "u64_digit")] #[inline] fn div(self, other: BigUint) -> BigUint { match other.data.len() { 0 => panic!(), 1 => From::from(self / other.data[0]), _ => Zero::zero(), } } } #[cfg(has_i128)] impl Div for BigUint { type Output = BigUint; #[inline] fn div(self, other: u128) -> BigUint { let (q, _) = self.div_rem(&From::from(other)); q } } #[cfg(has_i128)] impl DivAssign for BigUint { #[inline] fn div_assign(&mut self, other: u128) { *self = &*self / other; } } #[cfg(has_i128)] impl Div for u128 { type Output = BigUint; #[cfg(not(feature = "u64_digit"))] #[inline] fn div(self, other: BigUint) -> BigUint { match other.data.len() { 0 => panic!(), 1 => From::from(self / other.data[0] as u128), 2 => From::from( self / big_digit::to_doublebigdigit(other.data[1], other.data[0]) as u128, ), 3 => From::from(self / u32_to_u128(0, other.data[2], other.data[1], other.data[0])), 4 => From::from( self / u32_to_u128(other.data[3], other.data[2], other.data[1], other.data[0]), ), _ => Zero::zero(), } } #[cfg(feature = "u64_digit")] #[inline] fn div(self, other: BigUint) -> BigUint { match other.data.len() { 0 => panic!(), 1 => From::from(self / other.data[0] as u128), 2 => From::from(self / big_digit::to_doublebigdigit(other.data[1], other.data[0])), _ => Zero::zero(), } } } forward_all_binop_to_ref_ref!(impl Rem for BigUint, rem); forward_val_assign!(impl RemAssign for BigUint, rem_assign); impl<'a, 'b> Rem<&'b BigUint> for &'a BigUint { type Output = BigUint; #[inline] fn rem(self, other: &BigUint) -> BigUint { let (_, r) = self.div_rem(other); r } } impl<'a> RemAssign<&'a BigUint> for BigUint { #[inline] fn rem_assign(&mut self, other: &BigUint) { *self = &*self % other; } } promote_unsigned_scalars!(impl Rem for BigUint, rem); promote_unsigned_scalars_assign!(impl RemAssign for BigUint, rem_assign); forward_all_scalar_binop_to_val_val!(impl Rem for BigUint, rem); forward_all_scalar_binop_to_val_val!(impl Rem for BigUint, rem); #[cfg(has_i128)] forward_all_scalar_binop_to_val_val!(impl Rem for BigUint, rem); impl Rem for BigUint { type Output = BigUint; #[inline] fn rem(self, other: u32) -> BigUint { let (_, r) = div_rem_digit(self, other as BigDigit); From::from(r) } } impl RemAssign for BigUint { #[inline] fn rem_assign(&mut self, other: u32) { *self = &*self % other; } } impl Rem for u32 { type Output = BigUint; #[inline] fn rem(mut self, other: BigUint) -> BigUint { self %= other; From::from(self) } } macro_rules! impl_rem_assign_scalar { ($scalar:ty, $to_scalar:ident) => { forward_val_assign_scalar!(impl RemAssign for BigUint, $scalar, rem_assign); impl<'a> RemAssign<&'a BigUint> for $scalar { #[inline] fn rem_assign(&mut self, other: &BigUint) { *self = match other.$to_scalar() { None => *self, Some(0) => panic!(), Some(v) => *self % v }; } } } } // we can scalar %= BigUint for any scalar, including signed types #[cfg(has_i128)] impl_rem_assign_scalar!(u128, to_u128); impl_rem_assign_scalar!(usize, to_usize); impl_rem_assign_scalar!(u64, to_u64); impl_rem_assign_scalar!(u32, to_u32); impl_rem_assign_scalar!(u16, to_u16); impl_rem_assign_scalar!(u8, to_u8); #[cfg(has_i128)] impl_rem_assign_scalar!(i128, to_i128); impl_rem_assign_scalar!(isize, to_isize); impl_rem_assign_scalar!(i64, to_i64); impl_rem_assign_scalar!(i32, to_i32); impl_rem_assign_scalar!(i16, to_i16); impl_rem_assign_scalar!(i8, to_i8); impl Rem for BigUint { type Output = BigUint; #[inline] fn rem(self, other: u64) -> BigUint { let (_, r) = self.div_rem(&From::from(other)); r } } impl RemAssign for BigUint { #[inline] fn rem_assign(&mut self, other: u64) { *self = &*self % other; } } impl Rem for u64 { type Output = BigUint; #[inline] fn rem(mut self, other: BigUint) -> BigUint { self %= other; From::from(self) } } #[cfg(has_i128)] impl Rem for BigUint { type Output = BigUint; #[inline] fn rem(self, other: u128) -> BigUint { let (_, r) = self.div_rem(&From::from(other)); r } } #[cfg(has_i128)] impl RemAssign for BigUint { #[inline] fn rem_assign(&mut self, other: u128) { *self = &*self % other; } } #[cfg(has_i128)] impl Rem for u128 { type Output = BigUint; #[inline] fn rem(mut self, other: BigUint) -> BigUint { self %= other; From::from(self) } } impl Neg for BigUint { type Output = BigUint; #[inline] fn neg(self) -> BigUint { panic!() } } impl<'a> Neg for &'a BigUint { type Output = BigUint; #[inline] fn neg(self) -> BigUint { panic!() } } impl CheckedAdd for BigUint { #[inline] fn checked_add(&self, v: &BigUint) -> Option { Some(self.add(v)) } } impl CheckedSub for BigUint { #[inline] fn checked_sub(&self, v: &BigUint) -> Option { match self.cmp(v) { Less => None, Equal => Some(Zero::zero()), Greater => Some(self.sub(v)), } } } impl CheckedMul for BigUint { #[inline] fn checked_mul(&self, v: &BigUint) -> Option { Some(self.mul(v)) } } impl CheckedDiv for BigUint { #[inline] fn checked_div(&self, v: &BigUint) -> Option { if v.is_zero() { None } else { Some(self.div(v)) } } } impl Integer for BigUint { #[inline] fn div_rem(&self, other: &BigUint) -> (BigUint, BigUint) { div_rem(self, other) } #[inline] fn div_floor(&self, other: &BigUint) -> BigUint { let (d, _) = div_rem(self, other); d } #[inline] fn mod_floor(&self, other: &BigUint) -> BigUint { let (_, m) = div_rem(self, other); m } #[inline] fn div_mod_floor(&self, other: &BigUint) -> (BigUint, BigUint) { div_rem(self, other) } /// Calculates the Greatest Common Divisor (GCD) of the number and `other`. /// /// The result is always positive. #[inline] fn gcd(&self, other: &Self) -> Self { let (res, _, _) = extended_gcd(Cow::Borrowed(self), Cow::Borrowed(other), false); res.into_biguint().unwrap() } /// Calculates the Lowest Common Multiple (LCM) of the number and `other`. #[inline] fn lcm(&self, other: &BigUint) -> BigUint { self / self.gcd(other) * other } /// Deprecated, use `is_multiple_of` instead. #[inline] fn divides(&self, other: &BigUint) -> bool { self.is_multiple_of(other) } /// Returns `true` if the number is a multiple of `other`. #[inline] fn is_multiple_of(&self, other: &BigUint) -> bool { (self % other).is_zero() } /// Returns `true` if the number is divisible by `2`. #[inline] fn is_even(&self) -> bool { // Considering only the last digit. match self.data.first() { Some(x) => x.is_even(), None => true, } } /// Returns `true` if the number is not divisible by `2`. #[inline] fn is_odd(&self) -> bool { !self.is_even() } } #[inline] fn fixpoint(mut x: BigUint, max_bits: usize, f: F) -> BigUint where F: Fn(&BigUint) -> BigUint, { let mut xn = f(&x); // If the value increased, then the initial guess must have been low. // Repeat until we reverse course. while x < xn { // Sometimes an increase will go way too far, especially with large // powers, and then take a long time to walk back. We know an upper // bound based on bit size, so saturate on that. x = if xn.bits() > max_bits { BigUint::one() << max_bits } else { xn }; xn = f(&x); } // Now keep repeating while the estimate is decreasing. while x > xn { x = xn; xn = f(&x); } x } impl Roots for BigUint { // nth_root, sqrt and cbrt use Newton's method to compute // principal root of a given degree for a given integer. // Reference: // Brent & Zimmermann, Modern Computer Arithmetic, v0.5.9, Algorithm 1.14 fn nth_root(&self, n: u32) -> Self { assert!(n > 0, "root degree n must be at least 1"); if self.is_zero() || self.is_one() { return self.clone(); } match n { // Optimize for small n 1 => return self.clone(), 2 => return self.sqrt(), 3 => return self.cbrt(), _ => (), } // The root of non-zero values less than 2ⁿ can only be 1. let bits = self.bits(); if bits <= n as usize { return BigUint::one(); } // If we fit in `u64`, compute the root that way. if let Some(x) = self.to_u64() { return x.nth_root(n).into(); } let max_bits = bits / n as usize + 1; let guess = if let Some(f) = self.to_f64() { // We fit in `f64` (lossy), so get a better initial guess from that. BigUint::from_f64(exp(ln(f) / f64::from(n))).unwrap() } else { // Try to guess by scaling down such that it does fit in `f64`. // With some (x * 2ⁿᵏ), its nth root ≈ (ⁿ√x * 2ᵏ) let nsz = n as usize; let extra_bits = bits - (f64::MAX_EXP as usize - 1); let root_scale = (extra_bits + (nsz - 1)) / nsz; let scale = root_scale * nsz; if scale < bits && bits - scale > nsz { (self >> scale).nth_root(n) << root_scale } else { BigUint::one() << max_bits } }; let n_min_1 = n - 1; fixpoint(guess, max_bits, move |s| { let q = self / s.pow(n_min_1); let t = n_min_1 * s + q; t / n }) } // Reference: // Brent & Zimmermann, Modern Computer Arithmetic, v0.5.9, Algorithm 1.13 fn sqrt(&self) -> Self { if self.is_zero() || self.is_one() { return self.clone(); } // If we fit in `u64`, compute the root that way. if let Some(x) = self.to_u64() { return x.sqrt().into(); } let bits = self.bits(); let max_bits = bits / 2 as usize + 1; let guess = if let Some(f) = self.to_f64() { // We fit in `f64` (lossy), so get a better initial guess from that. BigUint::from_f64(sqrt(f)).unwrap() } else { // Try to guess by scaling down such that it does fit in `f64`. // With some (x * 2²ᵏ), its sqrt ≈ (√x * 2ᵏ) let extra_bits = bits - (f64::MAX_EXP as usize - 1); let root_scale = (extra_bits + 1) / 2; let scale = root_scale * 2; (self >> scale).sqrt() << root_scale }; fixpoint(guess, max_bits, move |s| { let q = self / s; let t = s + q; t >> 1 }) } fn cbrt(&self) -> Self { if self.is_zero() || self.is_one() { return self.clone(); } // If we fit in `u64`, compute the root that way. if let Some(x) = self.to_u64() { return x.cbrt().into(); } let bits = self.bits(); let max_bits = bits / 3 as usize + 1; let guess = if let Some(f) = self.to_f64() { // We fit in `f64` (lossy), so get a better initial guess from that. BigUint::from_f64(cbrt(f)).unwrap() } else { // Try to guess by scaling down such that it does fit in `f64`. // With some (x * 2³ᵏ), its cbrt ≈ (∛x * 2ᵏ) let extra_bits = bits - (f64::MAX_EXP as usize - 1); let root_scale = (extra_bits + 2) / 3; let scale = root_scale * 3; (self >> scale).cbrt() << root_scale }; fixpoint(guess, max_bits, move |s| { let q = self / (s * s); let t = (s << 1) + q; t / 3u32 }) } } fn high_bits_to_u64(v: &BigUint) -> u64 { match v.data.len() { 0 => 0, 1 => v.data[0] as u64, _ => { let mut bits = v.bits(); let mut ret = 0u64; let mut ret_bits = 0; for d in v.data.iter().rev() { let digit_bits = (bits - 1) % big_digit::BITS + 1; let bits_want = cmp::min(64 - ret_bits, digit_bits); if bits_want != 64 { ret <<= bits_want; } ret |= *d as u64 >> (digit_bits - bits_want); ret_bits += bits_want; bits -= bits_want; if ret_bits == 64 { break; } } ret } } } impl ToPrimitive for BigUint { #[inline] fn to_i64(&self) -> Option { self.to_u64().as_ref().and_then(u64::to_i64) } #[inline] #[cfg(has_i128)] fn to_i128(&self) -> Option { self.to_u128().as_ref().and_then(u128::to_i128) } #[inline] fn to_u64(&self) -> Option { let mut ret: u64 = 0; let mut bits = 0; for i in self.data.iter() { if bits >= 64 { return None; } ret += (*i as u64) << bits; bits += big_digit::BITS; } Some(ret) } #[inline] #[cfg(has_i128)] fn to_u128(&self) -> Option { let mut ret: u128 = 0; let mut bits = 0; for i in self.data.iter() { if bits >= 128 { return None; } ret |= (*i as u128) << bits; bits += big_digit::BITS; } Some(ret) } #[inline] fn to_f32(&self) -> Option { let mantissa = high_bits_to_u64(self); let exponent = self.bits() - fls(mantissa); if exponent > f32::MAX_EXP as usize { None } else { let ret = (mantissa as f32) * 2.0f32.powi(exponent as i32); if ret.is_infinite() { None } else { Some(ret) } } } #[inline] fn to_f64(&self) -> Option { let mantissa = high_bits_to_u64(self); let exponent = self.bits() - fls(mantissa); if exponent > f64::MAX_EXP as usize { None } else { let ret = (mantissa as f64) * 2.0f64.powi(exponent as i32); if ret.is_infinite() { None } else { Some(ret) } } } } impl FromPrimitive for BigUint { #[inline] fn from_i64(n: i64) -> Option { if n >= 0 { Some(BigUint::from(n as u64)) } else { None } } #[inline] #[cfg(has_i128)] fn from_i128(n: i128) -> Option { if n >= 0 { Some(BigUint::from(n as u128)) } else { None } } #[inline] fn from_u64(n: u64) -> Option { Some(BigUint::from(n)) } #[inline] #[cfg(has_i128)] fn from_u128(n: u128) -> Option { Some(BigUint::from(n)) } #[inline] fn from_f64(mut n: f64) -> Option { // handle NAN, INFINITY, NEG_INFINITY if !n.is_finite() { return None; } // match the rounding of casting from float to int n = FloatCore::trunc(n); // handle 0.x, -0.x if n.is_zero() { return Some(BigUint::zero()); } let (mantissa, exponent, sign) = FloatCore::integer_decode(n); if sign == -1 { return None; } let mut ret = BigUint::from(mantissa); if exponent > 0 { ret = ret << exponent as usize; } else if exponent < 0 { ret = ret >> (-exponent) as usize; } Some(ret) } } #[cfg(not(feature = "u64_digit"))] impl From for BigUint { #[inline] fn from(mut n: u64) -> Self { let mut ret: BigUint = Zero::zero(); while n != 0 { ret.data.push(n as BigDigit); // don't overflow if BITS is 64: n = (n >> 1) >> (big_digit::BITS - 1); } ret } } #[cfg(feature = "u64_digit")] impl From for BigUint { #[inline] fn from(n: u64) -> Self { BigUint::new_native(smallvec![n]) } } #[cfg(has_i128)] impl From for BigUint { #[inline] fn from(mut n: u128) -> Self { let mut ret: BigUint = Zero::zero(); while n != 0 { ret.data.push(n as BigDigit); n >>= big_digit::BITS; } ret } } macro_rules! impl_biguint_from_uint { ($T:ty) => { impl From<$T> for BigUint { #[inline] fn from(n: $T) -> Self { BigUint::from(n as u64) } } }; } impl_biguint_from_uint!(u8); impl_biguint_from_uint!(u16); impl_biguint_from_uint!(u32); impl_biguint_from_uint!(usize); /// A generic trait for converting a value to a `BigUint`. pub trait ToBigUint { /// Converts the value of `self` to a `BigUint`. fn to_biguint(&self) -> Option; } impl ToBigUint for BigUint { #[inline] fn to_biguint(&self) -> Option { Some(self.clone()) } } /// A generic trait for converting a value to a `BigUint`, and consuming the value. pub trait IntoBigUint { /// Converts the value of `self` to a `BigUint`. fn into_biguint(self) -> Option; } impl IntoBigUint for BigUint { #[inline] fn into_biguint(self) -> Option { Some(self) } } macro_rules! impl_to_biguint { ($T:ty, $from_ty:path) => { impl ToBigUint for $T { #[inline] fn to_biguint(&self) -> Option { $from_ty(*self) } } impl IntoBigUint for $T { #[inline] fn into_biguint(self) -> Option { $from_ty(self) } } }; } impl_to_biguint!(isize, FromPrimitive::from_isize); impl_to_biguint!(i8, FromPrimitive::from_i8); impl_to_biguint!(i16, FromPrimitive::from_i16); impl_to_biguint!(i32, FromPrimitive::from_i32); impl_to_biguint!(i64, FromPrimitive::from_i64); #[cfg(has_i128)] impl_to_biguint!(i128, FromPrimitive::from_i128); impl_to_biguint!(usize, FromPrimitive::from_usize); impl_to_biguint!(u8, FromPrimitive::from_u8); impl_to_biguint!(u16, FromPrimitive::from_u16); impl_to_biguint!(u32, FromPrimitive::from_u32); impl_to_biguint!(u64, FromPrimitive::from_u64); #[cfg(has_i128)] impl_to_biguint!(u128, FromPrimitive::from_u128); impl_to_biguint!(f32, FromPrimitive::from_f32); impl_to_biguint!(f64, FromPrimitive::from_f64); // Extract bitwise digits that evenly divide BigDigit fn to_bitwise_digits_le(u: &BigUint, bits: usize) -> Vec { debug_assert!(!u.is_zero() && bits <= 8 && big_digit::BITS % bits == 0); let last_i = u.data.len() - 1; let mask: BigDigit = (1 << bits) - 1; let digits_per_big_digit = big_digit::BITS / bits; let digits = (u.bits() + bits - 1) / bits; let mut res = Vec::with_capacity(digits); for mut r in u.data[..last_i].iter().cloned() { for _ in 0..digits_per_big_digit { res.push((r & mask) as u8); r >>= bits; } } let mut r = u.data[last_i]; while r != 0 { res.push((r & mask) as u8); r >>= bits; } res } // Extract bitwise digits that don't evenly divide BigDigit fn to_inexact_bitwise_digits_le(u: &BigUint, bits: usize) -> Vec { debug_assert!(!u.is_zero() && bits <= 8 && big_digit::BITS % bits != 0); let mask: BigDigit = (1 << bits) - 1; let digits = (u.bits() + bits - 1) / bits; let mut res = Vec::with_capacity(digits); let mut r = 0; let mut rbits = 0; for c in &u.data { r |= *c << rbits; rbits += big_digit::BITS; while rbits >= bits { res.push((r & mask) as u8); r >>= bits; // r had more bits than it could fit - grab the bits we lost if rbits > big_digit::BITS { r = *c >> (big_digit::BITS - (rbits - bits)); } rbits -= bits; } } if rbits != 0 { res.push(r as u8); } while let Some(&0) = res.last() { res.pop(); } res } // Extract little-endian radix digits #[inline(always)] // forced inline to get const-prop for radix=10 fn to_radix_digits_le(u: &BigUint, radix: u32) -> Vec { debug_assert!(!u.is_zero() && !radix.is_power_of_two()); // Estimate how big the result will be, so we can pre-allocate it. let bits = ilog2(radix); let radix_digits = idiv_ceil(u.bits(), bits); let mut res = Vec::with_capacity(radix_digits as usize); let mut digits = u.clone(); let (base, power) = get_radix_base(radix); let radix = radix as BigDigit; while digits.data.len() > 1 { let (q, mut r) = div_rem_digit(digits, base); for _ in 0..power { res.push((r % radix) as u8); r /= radix; } digits = q; } let mut r = digits.data[0]; while r != 0 { res.push((r % radix) as u8); r /= radix; } res } pub fn to_radix_le(u: &BigUint, radix: u32) -> Vec { if u.is_zero() { vec![0] } else if radix.is_power_of_two() { // Powers of two can use bitwise masks and shifting instead of division let bits = ilog2(radix); if big_digit::BITS % bits == 0 { to_bitwise_digits_le(u, bits) } else { to_inexact_bitwise_digits_le(u, bits) } } else if radix == 10 { // 10 is so common that it's worth separating out for const-propagation. // Optimizers can often turn constant division into a faster multiplication. to_radix_digits_le(u, 10) } else { to_radix_digits_le(u, radix) } } pub fn to_str_radix_reversed(u: &BigUint, radix: u32) -> Vec { assert!(2 <= radix && radix <= 36, "The radix must be within 2...36"); if u.is_zero() { return vec![b'0']; } let mut res = to_radix_le(u, radix); // Now convert everything to ASCII digits. for r in &mut res { debug_assert!((*r as u32) < radix); if *r < 10 { *r += b'0'; } else { *r += b'a' - 10; } } res } #[cfg(not(feature = "u64_digit"))] #[inline] fn ensure_big_digit(raw: Vec) -> SmallVec<[BigDigit; VEC_SIZE]> { raw.into() } #[cfg(feature = "u64_digit")] #[inline] fn ensure_big_digit(raw: Vec) -> SmallVec<[BigDigit; VEC_SIZE]> { ensure_big_digit_slice(&raw) } #[cfg(feature = "u64_digit")] #[inline] fn ensure_big_digit_slice(raw: &[u32]) -> SmallVec<[BigDigit; VEC_SIZE]> { raw.chunks(2) .map(|chunk| { // raw could have odd length if chunk.len() < 2 { chunk[0] as BigDigit } else { BigDigit::from(chunk[0]) | (BigDigit::from(chunk[1]) << 32) } }) .collect() } impl BigUint { /// Creates and initializes a `BigUint`. /// /// The digits are in little-endian base 232. #[inline] pub fn new(digits: Vec) -> BigUint { Self::new_native(ensure_big_digit(digits)) } /// Creates and initializes a `BigUint`. /// /// The digits are in little-endian base matching `BigDigit`. #[inline] pub fn new_native(digits: SmallVec<[BigDigit; VEC_SIZE]>) -> BigUint { BigUint { data: digits }.normalized() } /// Creates and initializes a `BigUint`. /// /// The digits are in little-endian base 232. #[inline] pub fn from_slice(slice: &[u32]) -> BigUint { BigUint::new(slice.to_vec()) } /// Creates and initializes a `BigUint`. /// /// The digits are in little-endian base matching `BigDigit` #[inline] pub fn from_slice_native(slice: &[BigDigit]) -> BigUint { BigUint::new_native(slice.into()) } pub fn get_limb(&self, i: usize) -> BigDigit { self.data[i] } /// Assign a value to a `BigUint`. /// /// The digits are in little-endian base 232. #[cfg(not(feature = "u64_digit"))] #[inline] pub fn assign_from_slice(&mut self, slice: &[u32]) { self.assign_from_slice_native(slice); } #[cfg(feature = "u64_digit")] #[inline] pub fn assign_from_slice(&mut self, slice: &[u32]) { let slice_digits = ensure_big_digit_slice(slice); self.assign_from_slice_native(&slice_digits); } /// Assign a value to a `BigUint`. /// /// The digits are in little-endian with the base matching `BigDigit`. #[inline] pub fn assign_from_slice_native(&mut self, slice: &[BigDigit]) { self.data.resize(slice.len(), 0); self.data.clone_from_slice(slice); self.normalize(); } /// Creates and initializes a `BigUint`. /// /// The bytes are in big-endian byte order. /// /// # Examples /// /// ``` /// use num_bigint_dig::BigUint; /// /// assert_eq!(BigUint::from_bytes_be(b"A"), /// BigUint::parse_bytes(b"65", 10).unwrap()); /// assert_eq!(BigUint::from_bytes_be(b"AA"), /// BigUint::parse_bytes(b"16705", 10).unwrap()); /// assert_eq!(BigUint::from_bytes_be(b"AB"), /// BigUint::parse_bytes(b"16706", 10).unwrap()); /// assert_eq!(BigUint::from_bytes_be(b"Hello world!"), /// BigUint::parse_bytes(b"22405534230753963835153736737", 10).unwrap()); /// ``` #[inline] pub fn from_bytes_be(bytes: &[u8]) -> BigUint { if bytes.is_empty() { Zero::zero() } else { let mut v = bytes.to_vec(); v.reverse(); BigUint::from_bytes_le(&*v) } } /// Creates and initializes a `BigUint`. /// /// The bytes are in little-endian byte order. #[inline] pub fn from_bytes_le(bytes: &[u8]) -> BigUint { if bytes.is_empty() { Zero::zero() } else { from_bitwise_digits_le(bytes, 8) } } /// Creates and initializes a `BigUint`. The input slice must contain /// ascii/utf8 characters in [0-9a-zA-Z]. /// `radix` must be in the range `2...36`. /// /// The function `from_str_radix` from the `Num` trait provides the same logic /// for `&str` buffers. /// /// # Examples /// /// ``` /// use num_bigint_dig::{BigUint, ToBigUint}; /// /// assert_eq!(BigUint::parse_bytes(b"1234", 10), ToBigUint::to_biguint(&1234)); /// assert_eq!(BigUint::parse_bytes(b"ABCD", 16), ToBigUint::to_biguint(&0xABCD)); /// assert_eq!(BigUint::parse_bytes(b"G", 16), None); /// ``` #[inline] pub fn parse_bytes(buf: &[u8], radix: u32) -> Option { str::from_utf8(buf) .ok() .and_then(|s| BigUint::from_str_radix(s, radix).ok()) } /// Creates and initializes a `BigUint`. Each u8 of the input slice is /// interpreted as one digit of the number /// and must therefore be less than `radix`. /// /// The bytes are in big-endian byte order. /// `radix` must be in the range `2...256`. /// /// # Examples /// /// ``` /// use num_bigint_dig::{BigUint}; /// /// let inbase190 = &[15, 33, 125, 12, 14]; /// let a = BigUint::from_radix_be(inbase190, 190).unwrap(); /// assert_eq!(a.to_radix_be(190), inbase190); /// ``` pub fn from_radix_be(buf: &[u8], radix: u32) -> Option { assert!( 2 <= radix && radix <= 256, "The radix must be within 2...256" ); if radix != 256 && buf.iter().any(|&b| b >= radix as u8) { return None; } let res = if radix.is_power_of_two() { // Powers of two can use bitwise masks and shifting instead of multiplication let bits = ilog2(radix); let mut v = Vec::from(buf); v.reverse(); if big_digit::BITS % bits == 0 { from_bitwise_digits_le(&v, bits) } else { from_inexact_bitwise_digits_le(&v, bits) } } else { from_radix_digits_be(buf, radix) }; Some(res) } /// Creates and initializes a `BigUint`. Each u8 of the input slice is /// interpreted as one digit of the number /// and must therefore be less than `radix`. /// /// The bytes are in little-endian byte order. /// `radix` must be in the range `2...256`. /// /// # Examples /// /// ``` /// use num_bigint_dig::{BigUint}; /// /// let inbase190 = &[14, 12, 125, 33, 15]; /// let a = BigUint::from_radix_be(inbase190, 190).unwrap(); /// assert_eq!(a.to_radix_be(190), inbase190); /// ``` pub fn from_radix_le(buf: &[u8], radix: u32) -> Option { assert!( 2 <= radix && radix <= 256, "The radix must be within 2...256" ); if radix != 256 && buf.iter().any(|&b| b >= radix as u8) { return None; } let res = if radix.is_power_of_two() { // Powers of two can use bitwise masks and shifting instead of multiplication let bits = ilog2(radix); if big_digit::BITS % bits == 0 { from_bitwise_digits_le(buf, bits) } else { from_inexact_bitwise_digits_le(buf, bits) } } else { let mut v = Vec::from(buf); v.reverse(); from_radix_digits_be(&v, radix) }; Some(res) } /// Returns the byte representation of the `BigUint` in big-endian byte order. /// /// # Examples /// /// ``` /// use num_bigint_dig::BigUint; /// /// let i = BigUint::parse_bytes(b"1125", 10).unwrap(); /// assert_eq!(i.to_bytes_be(), vec![4, 101]); /// ``` #[inline] pub fn to_bytes_be(&self) -> Vec { let mut v = self.to_bytes_le(); v.reverse(); v } /// Returns the byte representation of the `BigUint` in little-endian byte order. /// /// # Examples /// /// ``` /// use num_bigint_dig::BigUint; /// /// let i = BigUint::parse_bytes(b"1125", 10).unwrap(); /// assert_eq!(i.to_bytes_le(), vec![101, 4]); /// ``` #[inline] pub fn to_bytes_le(&self) -> Vec { if self.is_zero() { vec![0] } else { to_bitwise_digits_le(self, 8) } } /// Returns the integer formatted as a string in the given radix. /// `radix` must be in the range `2...36`. /// /// # Examples /// /// ``` /// use num_bigint_dig::BigUint; /// /// let i = BigUint::parse_bytes(b"ff", 16).unwrap(); /// assert_eq!(i.to_str_radix(16), "ff"); /// ``` #[inline] pub fn to_str_radix(&self, radix: u32) -> String { let mut v = to_str_radix_reversed(self, radix); v.reverse(); unsafe { String::from_utf8_unchecked(v) } } /// Returns the integer in the requested base in big-endian digit order. /// The output is not given in a human readable alphabet but as a zero /// based u8 number. /// `radix` must be in the range `2...256`. /// /// # Examples /// /// ``` /// use num_bigint_dig::BigUint; /// /// assert_eq!(BigUint::from(0xFFFFu64).to_radix_be(159), /// vec![2, 94, 27]); /// // 0xFFFF = 65535 = 2*(159^2) + 94*159 + 27 /// ``` #[inline] pub fn to_radix_be(&self, radix: u32) -> Vec { let mut v = to_radix_le(self, radix); v.reverse(); v } /// Returns the integer in the requested base in little-endian digit order. /// The output is not given in a human readable alphabet but as a zero /// based u8 number. /// `radix` must be in the range `2...256`. /// /// # Examples /// /// ``` /// use num_bigint_dig::BigUint; /// /// assert_eq!(BigUint::from(0xFFFFu64).to_radix_le(159), /// vec![27, 94, 2]); /// // 0xFFFF = 65535 = 27 + 94*159 + 2*(159^2) /// ``` #[inline] pub fn to_radix_le(&self, radix: u32) -> Vec { to_radix_le(self, radix) } /// Determines the fewest bits necessary to express the `BigUint`. #[inline] pub fn bits(&self) -> usize { if self.is_zero() { return 0; } let zeros = self.data.last().unwrap().leading_zeros(); self.data.len() * big_digit::BITS - zeros as usize } /// Strips off trailing zero bigdigits - comparisons require the last element in the vector to /// be nonzero. #[inline] pub(crate) fn normalize(&mut self) { while let Some(&0) = self.data.last() { self.data.pop(); } } /// Returns a normalized `BigUint`. #[inline] pub(crate) fn normalized(mut self) -> BigUint { self.normalize(); self } /// Returns `(self ^ exponent) % modulus`. /// /// Panics if the modulus is zero. pub fn modpow(&self, exponent: &Self, modulus: &Self) -> Self { assert!(!modulus.is_zero(), "divide by zero!"); // For an odd modulus, we can use Montgomery multiplication in base 2^32. if modulus.is_odd() { return monty_modpow(self, exponent, modulus); } // Otherwise do basically the same as `num::pow`, but with a modulus. let one = BigUint::one(); if exponent.is_zero() { return one; } let mut base = self % modulus; let mut exp = exponent.clone(); while exp.is_even() { base = &base * &base % modulus; exp >>= 1; } if exp == one { return base; } let mut acc = base.clone(); while exp > one { exp >>= 1; base = &base * &base % modulus; if exp.is_odd() { acc = acc * &base % modulus; } } acc } /// Returns the truncated principal square root of `self` -- /// see [Roots::sqrt](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#method.sqrt) pub fn sqrt(&self) -> Self { Roots::sqrt(self) } /// Returns the truncated principal cube root of `self` -- /// see [Roots::cbrt](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#method.cbrt). pub fn cbrt(&self) -> Self { Roots::cbrt(self) } /// Returns the truncated principal `n`th root of `self` -- /// see [Roots::nth_root](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#tymethod.nth_root). pub fn nth_root(&self, n: u32) -> Self { Roots::nth_root(self, n) } pub fn trailing_zeros(&self) -> Option { trailing_zeros(self) } /// Sets the value to the provided digit, reusing internal storage. pub fn set_digit(&mut self, digit: BigDigit) { if self.is_zero() { self.data.resize(1, digit); } else { self.data.resize(1, 0); self.data[0] = digit; } } } /// Returns the number of least-significant bits that are zero, /// or `None` if the entire number is zero. pub fn trailing_zeros(u: &BigUint) -> Option { u.data .iter() .enumerate() .find(|&(_, &digit)| digit != 0) .map(|(i, digit)| i * big_digit::BITS + digit.trailing_zeros() as usize) } impl_sum_iter_type!(BigUint); impl_product_iter_type!(BigUint); pub trait IntDigits { fn digits(&self) -> &[BigDigit]; fn digits_mut(&mut self) -> &mut SmallVec<[BigDigit; VEC_SIZE]>; fn normalize(&mut self); fn capacity(&self) -> usize; fn len(&self) -> usize; } impl IntDigits for BigUint { #[inline] fn digits(&self) -> &[BigDigit] { &self.data } #[inline] fn digits_mut(&mut self) -> &mut SmallVec<[BigDigit; VEC_SIZE]> { &mut self.data } #[inline] fn normalize(&mut self) { self.normalize(); } #[inline] fn capacity(&self) -> usize { self.data.capacity() } #[inline] fn len(&self) -> usize { self.data.len() } } /// Combine four `u32`s into a single `u128`. #[cfg(has_i128)] #[inline] #[allow(dead_code)] fn u32_to_u128(a: u32, b: u32, c: u32, d: u32) -> u128 { u128::from(d) | (u128::from(c) << 32) | (u128::from(b) << 64) | (u128::from(a) << 96) } /// Split a single `u128` into four `u32`. #[cfg(has_i128)] #[inline] #[allow(dead_code)] fn u32_from_u128(n: u128) -> (u32, u32, u32, u32) { ( (n >> 96) as u32, (n >> 64) as u32, (n >> 32) as u32, n as u32, ) } #[cfg(feature = "serde")] #[cfg(not(feature = "u64_digit"))] impl serde::Serialize for BigUint { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer, { // Note: do not change the serialization format, or it may break forward // and backward compatibility of serialized data! If we ever change the // internal representation, we should still serialize in base-`u32`. let data: &[u32] = &self.data.as_slice(); data.serialize(serializer) } } #[cfg(feature = "serde")] #[cfg(feature = "u64_digit")] impl serde::Serialize for BigUint { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer, { let last = if self.data.is_empty() { 0 } else { self.data.len() - 1 }; let data: Vec = self .data .iter() .enumerate() .flat_map(|(i, n)| { if i == last && n < &(u32::MAX as u64) { vec![*n as u32] } else { vec![*n as u32, (n >> 32) as u32] } }) .collect(); data.serialize(serializer) } } #[cfg(feature = "serde")] impl<'de> serde::Deserialize<'de> for BigUint { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, { let data: Vec = Vec::deserialize(deserializer)?; Ok(BigUint::new(data)) } } /// Returns the greatest power of the radix <= big_digit::BASE #[inline] fn get_radix_base(radix: u32) -> (BigDigit, usize) { debug_assert!( 2 <= radix && radix <= 256, "The radix must be within 2...256" ); debug_assert!(!radix.is_power_of_two()); // To generate this table: // for radix in 2u64..257 { // let mut power = big_digit::BITS / fls(radix as u64); // let mut base = radix.pow(power as u32); // // while let Some(b) = base.checked_mul(radix) { // if b > big_digit::MAX { // break; // } // base = b; // power += 1; // } // // println!("({:10}, {:2}), // {:2}", base, power, radix); // } // and // for radix in 2u64..257 { // let mut power = 64 / fls(radix as u64); // let mut base = radix.pow(power as u32); // // while let Some(b) = base.checked_mul(radix) { // base = b; // power += 1; // } // // println!("({:20}, {:2}), // {:2}", base, power, radix); // } match big_digit::BITS { 32 => { const BASES: [(u32, usize); 257] = [ (0, 0), (0, 0), (0, 0), // 2 (3_486_784_401, 20), // 3 (0, 0), // 4 (1_220_703_125, 13), // 5 (2_176_782_336, 12), // 6 (1_977_326_743, 11), // 7 (0, 0), // 8 (3_486_784_401, 10), // 9 (1_000_000_000, 9), // 10 (2_357_947_691, 9), // 11 (429_981_696, 8), // 12 (815_730_721, 8), // 13 (1_475_789_056, 8), // 14 (2_562_890_625, 8), // 15 (0, 0), // 16 (410_338_673, 7), // 17 (612_220_032, 7), // 18 (893_871_739, 7), // 19 (1_280_000_000, 7), // 20 (1_801_088_541, 7), // 21 (2_494_357_888, 7), // 22 (3_404_825_447, 7), // 23 (191_102_976, 6), // 24 (244_140_625, 6), // 25 (308_915_776, 6), // 26 (387_420_489, 6), // 27 (481_890_304, 6), // 28 (594_823_321, 6), // 29 (729_000_000, 6), // 30 (887_503_681, 6), // 31 (0, 0), // 32 (1_291_467_969, 6), // 33 (1_544_804_416, 6), // 34 (1_838_265_625, 6), // 35 (2_176_782_336, 6), // 36 (2_565_726_409, 6), // 37 (3_010_936_384, 6), // 38 (3_518_743_761, 6), // 39 (4_096_000_000, 6), // 40 (115_856_201, 5), // 41 (130_691_232, 5), // 42 (147_008_443, 5), // 43 (164_916_224, 5), // 44 (184_528_125, 5), // 45 (205_962_976, 5), // 46 (229_345_007, 5), // 47 (254_803_968, 5), // 48 (282_475_249, 5), // 49 (312_500_000, 5), // 50 (345_025_251, 5), // 51 (380_204_032, 5), // 52 (418_195_493, 5), // 53 (459_165_024, 5), // 54 (503_284_375, 5), // 55 (550_731_776, 5), // 56 (601_692_057, 5), // 57 (656_356_768, 5), // 58 (714_924_299, 5), // 59 (777_600_000, 5), // 60 (844_596_301, 5), // 61 (916_132_832, 5), // 62 (992_436_543, 5), // 63 (0, 0), // 64 (1_160_290_625, 5), // 65 (1_252_332_576, 5), // 66 (1_350_125_107, 5), // 67 (1_453_933_568, 5), // 68 (1_564_031_349, 5), // 69 (1_680_700_000, 5), // 70 (1_804_229_351, 5), // 71 (1_934_917_632, 5), // 72 (2_073_071_593, 5), // 73 (2_219_006_624, 5), // 74 (2_373_046_875, 5), // 75 (2_535_525_376, 5), // 76 (2_706_784_157, 5), // 77 (2_887_174_368, 5), // 78 (3_077_056_399, 5), // 79 (3_276_800_000, 5), // 80 (3_486_784_401, 5), // 81 (3_707_398_432, 5), // 82 (3_939_040_643, 5), // 83 (4_182_119_424, 5), // 84 (52_200_625, 4), // 85 (54_700_816, 4), // 86 (57_289_761, 4), // 87 (59_969_536, 4), // 88 (62_742_241, 4), // 89 (65_610_000, 4), // 90 (68_574_961, 4), // 91 (71_639_296, 4), // 92 (74_805_201, 4), // 93 (78_074_896, 4), // 94 (81_450_625, 4), // 95 (84_934_656, 4), // 96 (88_529_281, 4), // 97 (92_236_816, 4), // 98 (96_059_601, 4), // 99 (100_000_000, 4), // 100 (104_060_401, 4), // 101 (108_243_216, 4), // 102 (112_550_881, 4), // 103 (116_985_856, 4), // 104 (121_550_625, 4), // 105 (126_247_696, 4), // 106 (131_079_601, 4), // 107 (136_048_896, 4), // 108 (141_158_161, 4), // 109 (146_410_000, 4), // 110 (151_807_041, 4), // 111 (157_351_936, 4), // 112 (163_047_361, 4), // 113 (168_896_016, 4), // 114 (174_900_625, 4), // 115 (181_063_936, 4), // 116 (187_388_721, 4), // 117 (193_877_776, 4), // 118 (200_533_921, 4), // 119 (207_360_000, 4), // 120 (214_358_881, 4), // 121 (221_533_456, 4), // 122 (228_886_641, 4), // 123 (236_421_376, 4), // 124 (244_140_625, 4), // 125 (252_047_376, 4), // 126 (260_144_641, 4), // 127 (0, 0), // 128 (276_922_881, 4), // 129 (285_610_000, 4), // 130 (294_499_921, 4), // 131 (303_595_776, 4), // 132 (312_900_721, 4), // 133 (322_417_936, 4), // 134 (332_150_625, 4), // 135 (342_102_016, 4), // 136 (352_275_361, 4), // 137 (362_673_936, 4), // 138 (373_301_041, 4), // 139 (384_160_000, 4), // 140 (395_254_161, 4), // 141 (406_586_896, 4), // 142 (418_161_601, 4), // 143 (429_981_696, 4), // 144 (442_050_625, 4), // 145 (454_371_856, 4), // 146 (466_948_881, 4), // 147 (479_785_216, 4), // 148 (492_884_401, 4), // 149 (506_250_000, 4), // 150 (519_885_601, 4), // 151 (533_794_816, 4), // 152 (547_981_281, 4), // 153 (562_448_656, 4), // 154 (577_200_625, 4), // 155 (592_240_896, 4), // 156 (607_573_201, 4), // 157 (623_201_296, 4), // 158 (639_128_961, 4), // 159 (655_360_000, 4), // 160 (671_898_241, 4), // 161 (688_747_536, 4), // 162 (705_911_761, 4), // 163 (723_394_816, 4), // 164 (741_200_625, 4), // 165 (759_333_136, 4), // 166 (777_796_321, 4), // 167 (796_594_176, 4), // 168 (815_730_721, 4), // 169 (835_210_000, 4), // 170 (855_036_081, 4), // 171 (875_213_056, 4), // 172 (895_745_041, 4), // 173 (916_636_176, 4), // 174 (937_890_625, 4), // 175 (959_512_576, 4), // 176 (981_506_241, 4), // 177 (1_003_875_856, 4), // 178 (1_026_625_681, 4), // 179 (1_049_760_000, 4), // 180 (1_073_283_121, 4), // 181 (1_097_199_376, 4), // 182 (1_121_513_121, 4), // 183 (1_146_228_736, 4), // 184 (1_171_350_625, 4), // 185 (1_196_883_216, 4), // 186 (1_222_830_961, 4), // 187 (1_249_198_336, 4), // 188 (1_275_989_841, 4), // 189 (1_303_210_000, 4), // 190 (1_330_863_361, 4), // 191 (1_358_954_496, 4), // 192 (1_387_488_001, 4), // 193 (1_416_468_496, 4), // 194 (1_445_900_625, 4), // 195 (1_475_789_056, 4), // 196 (1_506_138_481, 4), // 197 (1_536_953_616, 4), // 198 (1_568_239_201, 4), // 199 (1_600_000_000, 4), // 200 (1_632_240_801, 4), // 201 (1_664_966_416, 4), // 202 (1_698_181_681, 4), // 203 (1_731_891_456, 4), // 204 (1_766_100_625, 4), // 205 (1_800_814_096, 4), // 206 (1_836_036_801, 4), // 207 (1_871_773_696, 4), // 208 (1_908_029_761, 4), // 209 (1_944_810_000, 4), // 210 (1_982_119_441, 4), // 211 (2_019_963_136, 4), // 212 (2_058_346_161, 4), // 213 (2_097_273_616, 4), // 214 (2_136_750_625, 4), // 215 (2_176_782_336, 4), // 216 (2_217_373_921, 4), // 217 (2_258_530_576, 4), // 218 (2_300_257_521, 4), // 219 (2_342_560_000, 4), // 220 (2_385_443_281, 4), // 221 (2_428_912_656, 4), // 222 (2_472_973_441, 4), // 223 (2_517_630_976, 4), // 224 (2_562_890_625, 4), // 225 (2_608_757_776, 4), // 226 (2_655_237_841, 4), // 227 (2_702_336_256, 4), // 228 (2_750_058_481, 4), // 229 (2_798_410_000, 4), // 230 (2_847_396_321, 4), // 231 (2_897_022_976, 4), // 232 (2_947_295_521, 4), // 233 (2_998_219_536, 4), // 234 (3_049_800_625, 4), // 235 (3_102_044_416, 4), // 236 (3_154_956_561, 4), // 237 (3_208_542_736, 4), // 238 (3_262_808_641, 4), // 239 (3_317_760_000, 4), // 240 (3_373_402_561, 4), // 241 (3_429_742_096, 4), // 242 (3_486_784_401, 4), // 243 (3_544_535_296, 4), // 244 (3_603_000_625, 4), // 245 (3_662_186_256, 4), // 246 (3_722_098_081, 4), // 247 (3_782_742_016, 4), // 248 (3_844_124_001, 4), // 249 (3_906_250_000, 4), // 250 (3_969_126_001, 4), // 251 (4_032_758_016, 4), // 252 (4_097_152_081, 4), // 253 (4_162_314_256, 4), // 254 (4_228_250_625, 4), // 255 (0, 0), // 256 ]; let (base, power) = BASES[radix as usize]; (base as BigDigit, power) } 64 => { const BASES: [(u64, usize); 257] = [ (0, 0), (0, 0), (9_223_372_036_854_775_808, 63), // 2 (12_157_665_459_056_928_801, 40), // 3 (4_611_686_018_427_387_904, 31), // 4 (7_450_580_596_923_828_125, 27), // 5 (4_738_381_338_321_616_896, 24), // 6 (3_909_821_048_582_988_049, 22), // 7 (9_223_372_036_854_775_808, 21), // 8 (12_157_665_459_056_928_801, 20), // 9 (10_000_000_000_000_000_000, 19), // 10 (5_559_917_313_492_231_481, 18), // 11 (2_218_611_106_740_436_992, 17), // 12 (8_650_415_919_381_337_933, 17), // 13 (2_177_953_337_809_371_136, 16), // 14 (6_568_408_355_712_890_625, 16), // 15 (1_152_921_504_606_846_976, 15), // 16 (2_862_423_051_509_815_793, 15), // 17 (6_746_640_616_477_458_432, 15), // 18 (15_181_127_029_874_798_299, 15), // 19 (1_638_400_000_000_000_000, 14), // 20 (3_243_919_932_521_508_681, 14), // 21 (6_221_821_273_427_820_544, 14), // 22 (11_592_836_324_538_749_809, 14), // 23 (876_488_338_465_357_824, 13), // 24 (1_490_116_119_384_765_625, 13), // 25 (2_481_152_873_203_736_576, 13), // 26 (4_052_555_153_018_976_267, 13), // 27 (6_502_111_422_497_947_648, 13), // 28 (10_260_628_712_958_602_189, 13), // 29 (15_943_230_000_000_000_000, 13), // 30 (787_662_783_788_549_761, 12), // 31 (1_152_921_504_606_846_976, 12), // 32 (1_667_889_514_952_984_961, 12), // 33 (2_386_420_683_693_101_056, 12), // 34 (3_379_220_508_056_640_625, 12), // 35 (4_738_381_338_321_616_896, 12), // 36 (6_582_952_005_840_035_281, 12), // 37 (9_065_737_908_494_995_456, 12), // 38 (12_381_557_655_576_425_121, 12), // 39 (16_777_216_000_000_000_000, 12), // 40 (550_329_031_716_248_441, 11), // 41 (717_368_321_110_468_608, 11), // 42 (929_293_739_471_222_707, 11), // 43 (1_196_683_881_290_399_744, 11), // 44 (1_532_278_301_220_703_125, 11), // 45 (1_951_354_384_207_722_496, 11), // 46 (2_472_159_215_084_012_303, 11), // 47 (3_116_402_981_210_161_152, 11), // 48 (3_909_821_048_582_988_049, 11), // 49 (4_882_812_500_000_000_000, 11), // 50 (6_071_163_615_208_263_051, 11), // 51 (7_516_865_509_350_965_248, 11), // 52 (9_269_035_929_372_191_597, 11), // 53 (11_384_956_040_305_711_104, 11), // 54 (13_931_233_916_552_734_375, 11), // 55 (16_985_107_389_382_393_856, 11), // 56 (362_033_331_456_891_249, 10), // 57 (430_804_206_899_405_824, 10), // 58 (511_116_753_300_641_401, 10), // 59 (604_661_760_000_000_000, 10), // 60 (713_342_911_662_882_601, 10), // 61 (839_299_365_868_340_224, 10), // 62 (984_930_291_881_790_849, 10), // 63 (1_152_921_504_606_846_976, 10), // 64 (1_346_274_334_462_890_625, 10), // 65 (1_568_336_880_910_795_776, 10), // 66 (1_822_837_804_551_761_449, 10), // 67 (2_113_922_820_157_210_624, 10), // 68 (2_446_194_060_654_759_801, 10), // 69 (2_824_752_490_000_000_000, 10), // 70 (3_255_243_551_009_881_201, 10), // 71 (3_743_906_242_624_487_424, 10), // 72 (4_297_625_829_703_557_649, 10), // 73 (4_923_990_397_355_877_376, 10), // 74 (5_631_351_470_947_265_625, 10), // 75 (6_428_888_932_339_941_376, 10), // 76 (7_326_680_472_586_200_649, 10), // 77 (8_335_775_831_236_199_424, 10), // 78 (9_468_276_082_626_847_201, 10), // 79 (10_737_418_240_000_000_000, 10), // 80 (12_157_665_459_056_928_801, 10), // 81 (13_744_803_133_596_058_624, 10), // 82 (15_516_041_187_205_853_449, 10), // 83 (17_490_122_876_598_091_776, 10), // 84 (231_616_946_283_203_125, 9), // 85 (257_327_417_311_663_616, 9), // 86 (285_544_154_243_029_527, 9), // 87 (316_478_381_828_866_048, 9), // 88 (350_356_403_707_485_209, 9), // 89 (387_420_489_000_000_000, 9), // 90 (427_929_800_129_788_411, 9), // 91 (472_161_363_286_556_672, 9), // 92 (520_411_082_988_487_293, 9), // 93 (572_994_802_228_616_704, 9), // 94 (630_249_409_724_609_375, 9), // 95 (692_533_995_824_480_256, 9), // 96 (760_231_058_654_565_217, 9), // 97 (833_747_762_130_149_888, 9), // 98 (913_517_247_483_640_899, 9), // 99 (1_000_000_000_000_000_000, 9), // 100 (1_093_685_272_684_360_901, 9), // 101 (1_195_092_568_622_310_912, 9), // 102 (1_304_773_183_829_244_583, 9), // 103 (1_423_311_812_421_484_544, 9), // 104 (1_551_328_215_978_515_625, 9), // 105 (1_689_478_959_002_692_096, 9), // 106 (1_838_459_212_420_154_507, 9), // 107 (1_999_004_627_104_432_128, 9), // 108 (2_171_893_279_442_309_389, 9), // 109 (2_357_947_691_000_000_000, 9), // 110 (2_558_036_924_386_500_591, 9), // 111 (2_773_078_757_450_186_752, 9), // 112 (3_004_041_937_984_268_273, 9), // 113 (3_251_948_521_156_637_184, 9), // 114 (3_517_876_291_919_921_875, 9), // 115 (3_802_961_274_698_203_136, 9), // 116 (4_108_400_332_687_853_397, 9), // 117 (4_435_453_859_151_328_768, 9), // 118 (4_785_448_563_124_474_679, 9), // 119 (5_159_780_352_000_000_000, 9), // 120 (5_559_917_313_492_231_481, 9), // 121 (5_987_402_799_531_080_192, 9), // 122 (6_443_858_614_676_334_363, 9), // 123 (6_930_988_311_686_938_624, 9), // 124 (7_450_580_596_923_828_125, 9), // 125 (8_004_512_848_309_157_376, 9), // 126 (8_594_754_748_609_397_887, 9), // 127 (9_223_372_036_854_775_808, 9), // 128 (9_892_530_380_752_880_769, 9), // 129 (10_604_499_373_000_000_000, 9), // 130 (11_361_656_654_439_817_571, 9), // 131 (12_166_492_167_065_567_232, 9), // 132 (13_021_612_539_908_538_853, 9), // 133 (13_929_745_610_903_012_864, 9), // 134 (14_893_745_087_865_234_375, 9), // 135 (15_916_595_351_771_938_816, 9), // 136 (17_001_416_405_572_203_977, 9), // 137 (18_151_468_971_815_029_248, 9), // 138 (139_353_667_211_683_681, 8), // 139 (147_578_905_600_000_000, 8), // 140 (156_225_851_787_813_921, 8), // 141 (165_312_903_998_914_816, 8), // 142 (174_859_124_550_883_201, 8), // 143 (184_884_258_895_036_416, 8), // 144 (195_408_755_062_890_625, 8), // 145 (206_453_783_524_884_736, 8), // 146 (218_041_257_467_152_161, 8), // 147 (230_193_853_492_166_656, 8), // 148 (242_935_032_749_128_801, 8), // 149 (256_289_062_500_000_000, 8), // 150 (270_281_038_127_131_201, 8), // 151 (284_936_905_588_473_856, 8), // 152 (300_283_484_326_400_961, 8), // 153 (316_348_490_636_206_336, 8), // 154 (333_160_561_500_390_625, 8), // 155 (350_749_278_894_882_816, 8), // 156 (369_145_194_573_386_401, 8), // 157 (388_379_855_336_079_616, 8), // 158 (408_485_828_788_939_521, 8), // 159 (429_496_729_600_000_000, 8), // 160 (451_447_246_258_894_081, 8), // 161 (474_373_168_346_071_296, 8), // 162 (498_311_414_318_121_121, 8), // 163 (523_300_059_815_673_856, 8), // 164 (549_378_366_500_390_625, 8), // 165 (576_586_811_427_594_496, 8), // 166 (604_967_116_961_135_041, 8), // 167 (634_562_281_237_118_976, 8), // 168 (665_416_609_183_179_841, 8), // 169 (697_575_744_100_000_000, 8), // 170 (731_086_699_811_838_561, 8), // 171 (765_997_893_392_859_136, 8), // 172 (802_359_178_476_091_681, 8), // 173 (840_221_879_151_902_976, 8), // 174 (879_638_824_462_890_625, 8), // 175 (920_664_383_502_155_776, 8), // 176 (963_354_501_121_950_081, 8), // 177 (1_007_766_734_259_732_736, 8), // 178 (1_053_960_288_888_713_761, 8), // 179 (1_101_996_057_600_000_000, 8), // 180 (1_151_936_657_823_500_641, 8), // 181 (1_203_846_470_694_789_376, 8), // 182 (1_257_791_680_575_160_641, 8), // 183 (1_313_840_315_232_157_696, 8), // 184 (1_372_062_286_687_890_625, 8), // 185 (1_432_529_432_742_502_656, 8), // 186 (1_495_315_559_180_183_521, 8), // 187 (1_560_496_482_665_168_896, 8), // 188 (1_628_150_074_335_205_281, 8), // 189 (1_698_356_304_100_000_000, 8), // 190 (1_771_197_285_652_216_321, 8), // 191 (1_846_757_322_198_614_016, 8), // 192 (1_925_122_952_918_976_001, 8), // 193 (2_006_383_000_160_502_016, 8), // 194 (2_090_628_617_375_390_625, 8), // 195 (2_177_953_337_809_371_136, 8), // 196 (2_268_453_123_948_987_361, 8), // 197 (2_362_226_417_735_475_456, 8), // 198 (2_459_374_191_553_118_401, 8), // 199 (2_560_000_000_000_000_000, 8), // 200 (2_664_210_032_449_121_601, 8), // 201 (2_772_113_166_407_885_056, 8), // 202 (2_883_821_021_683_985_761, 8), // 203 (2_999_448_015_365_799_936, 8), // 204 (3_119_111_417_625_390_625, 8), // 205 (3_242_931_408_352_297_216, 8), // 206 (3_371_031_134_626_313_601, 8), // 207 (3_503_536_769_037_500_416, 8), // 208 (3_640_577_568_861_717_121, 8), // 209 (3_782_285_936_100_000_000, 8), // 210 (3_928_797_478_390_152_481, 8), // 211 (4_080_251_070_798_954_496, 8), // 212 (4_236_788_918_503_437_921, 8), // 213 (4_398_556_620_369_715_456, 8), // 214 (4_565_703_233_437_890_625, 8), // 215 (4_738_381_338_321_616_896, 8), // 216 (4_916_747_105_530_914_241, 8), // 217 (5_100_960_362_726_891_776, 8), // 218 (5_291_184_662_917_065_441, 8), // 219 (5_487_587_353_600_000_000, 8), // 220 (5_690_339_646_868_044_961, 8), // 221 (5_899_616_690_476_974_336, 8), // 222 (6_115_597_639_891_380_481, 8), // 223 (6_338_465_731_314_712_576, 8), // 224 (6_568_408_355_712_890_625, 8), // 225 (6_805_617_133_840_466_176, 8), // 226 (7_050_287_992_278_341_281, 8), // 227 (7_302_621_240_492_097_536, 8), // 228 (7_562_821_648_920_027_361, 8), // 229 (7_831_098_528_100_000_000, 8), // 230 (8_107_665_808_844_335_041, 8), // 231 (8_392_742_123_471_896_576, 8), // 232 (8_686_550_888_106_661_441, 8), // 233 (8_989_320_386_052_055_296, 8), // 234 (9_301_283_852_250_390_625, 8), // 235 (9_622_679_558_836_781_056, 8), // 236 (9_953_750_901_796_946_721, 8), // 237 (10_294_746_488_738_365_696, 8), // 238 (10_645_920_227_784_266_881, 8), // 239 (11_007_531_417_600_000_000, 8), // 240 (11_379_844_838_561_358_721, 8), // 241 (11_763_130_845_074_473_216, 8), // 242 (12_157_665_459_056_928_801, 8), // 243 (12_563_730_464_589_807_616, 8), // 244 (12_981_613_503_750_390_625, 8), // 245 (13_411_608_173_635_297_536, 8), // 246 (13_854_014_124_583_882_561, 8), // 247 (14_309_137_159_611_744_256, 8), // 248 (14_777_289_335_064_248_001, 8), // 249 (15_258_789_062_500_000_000, 8), // 250 (15_753_961_211_814_252_001, 8), // 251 (16_263_137_215_612_256_256, 8), // 252 (16_786_655_174_842_630_561, 8), // 253 (17_324_859_965_700_833_536, 8), // 254 (17_878_103_347_812_890_625, 8), // 255 (72_057_594_037_927_936, 7), // 256 ]; let (base, power) = BASES[radix as usize]; (base as BigDigit, power) } _ => panic!("Invalid bigdigit size"), } } #[cfg(not(feature = "u64_digit"))] #[test] fn test_from_slice() { fn check(slice: &[u32], data: &[BigDigit]) { assert_eq!(&BigUint::from_slice(slice).data[..], data); } check(&[1], &[1]); check(&[0, 0, 0], &[]); check(&[1, 2, 0, 0], &[1, 2]); check(&[0, 0, 1, 2], &[0, 0, 1, 2]); check(&[0, 0, 1, 2, 0, 0], &[0, 0, 1, 2]); check(&[-1i32 as u32], &[-1i32 as BigDigit]); } #[cfg(feature = "u64_digit")] #[test] fn test_from_slice() { fn check(slice: &[u32], data: &[BigDigit]) { assert_eq!( &BigUint::from_slice(slice).data[..], data, "from {:?}, to {:?}", slice, data ); } check(&[1], &[1]); check(&[0, 0, 0], &[]); check(&[1, 2], &[8_589_934_593]); check(&[1, 2, 0, 0], &[8_589_934_593]); check(&[0, 0, 1, 2], &[0, 8_589_934_593]); check(&[0, 0, 1, 2, 0, 0], &[0, 8_589_934_593]); check(&[-1i32 as u32], &[(-1i32 as u32) as BigDigit]); } #[test] fn test_from_slice_native() { fn check(slice: &[BigDigit], data: &[BigDigit]) { assert!(&BigUint::from_slice_native(slice).data[..] == data); } check(&[1], &[1]); check(&[0, 0, 0], &[]); check(&[1, 2, 0, 0], &[1, 2]); check(&[0, 0, 1, 2], &[0, 0, 1, 2]); check(&[0, 0, 1, 2, 0, 0], &[0, 0, 1, 2]); check(&[-1i32 as BigDigit], &[-1i32 as BigDigit]); } #[test] fn test_assign_from_slice_native() { fn check(slice: &[BigDigit], data: &[BigDigit]) { let mut p = BigUint::from_slice_native(&[2627, 0, 9182, 42]); p.assign_from_slice_native(slice); assert!(&p.data[..] == data); } check(&[1], &[1]); check(&[0, 0, 0], &[]); check(&[1, 2, 0, 0], &[1, 2]); check(&[0, 0, 1, 2], &[0, 0, 1, 2]); check(&[0, 0, 1, 2, 0, 0], &[0, 0, 1, 2]); check(&[-1i32 as BigDigit], &[-1i32 as BigDigit]); } #[cfg(has_i128)] #[test] fn test_u32_u128() { assert_eq!(u32_from_u128(0u128), (0, 0, 0, 0)); assert_eq!( u32_from_u128(u128::max_value()), ( u32::max_value(), u32::max_value(), u32::max_value(), u32::max_value() ) ); assert_eq!( u32_from_u128(u32::max_value() as u128), (0, 0, 0, u32::max_value()) ); assert_eq!( u32_from_u128(u64::max_value() as u128), (0, 0, u32::max_value(), u32::max_value()) ); assert_eq!( u32_from_u128((u64::max_value() as u128) + u32::max_value() as u128), (0, 1, 0, u32::max_value() - 1) ); assert_eq!(u32_from_u128(36_893_488_151_714_070_528), (0, 2, 1, 0)); } #[cfg(has_i128)] #[test] fn test_u128_u32_roundtrip() { // roundtrips let values = vec![ 0u128, 1u128, u64::max_value() as u128 * 3, u32::max_value() as u128, u64::max_value() as u128, (u64::max_value() as u128) + u32::max_value() as u128, u128::max_value(), ]; for val in &values { let (a, b, c, d) = u32_from_u128(*val); assert_eq!(u32_to_u128(a, b, c, d), *val); } } // Mod Inverse impl<'a> ModInverse<&'a BigUint> for BigUint { type Output = BigInt; fn mod_inverse(self, m: &'a BigUint) -> Option { mod_inverse(Cow::Owned(self), Cow::Borrowed(m)) } } impl ModInverse for BigUint { type Output = BigInt; fn mod_inverse(self, m: BigUint) -> Option { mod_inverse(Cow::Owned(self), Cow::Owned(m)) } } impl<'a> ModInverse<&'a BigInt> for BigUint { type Output = BigInt; fn mod_inverse(self, m: &'a BigInt) -> Option { mod_inverse(Cow::Owned(self), Cow::Owned(m.to_biguint().unwrap())) } } impl ModInverse for BigUint { type Output = BigInt; fn mod_inverse(self, m: BigInt) -> Option { mod_inverse(Cow::Owned(self), Cow::Owned(m.into_biguint().unwrap())) } } impl<'a, 'b> ModInverse<&'b BigUint> for &'a BigUint { type Output = BigInt; fn mod_inverse(self, m: &'b BigUint) -> Option { mod_inverse(Cow::Borrowed(self), Cow::Borrowed(m)) } } impl<'a> ModInverse for &'a BigUint { type Output = BigInt; fn mod_inverse(self, m: BigUint) -> Option { mod_inverse(Cow::Borrowed(self), Cow::Owned(m)) } } impl<'a, 'b> ModInverse<&'b BigInt> for &'a BigUint { type Output = BigInt; fn mod_inverse(self, m: &'b BigInt) -> Option { mod_inverse(Cow::Borrowed(self), Cow::Owned(m.to_biguint().unwrap())) } } // Extended GCD impl<'a> ExtendedGcd<&'a BigUint> for BigUint { fn extended_gcd(self, other: &'a BigUint) -> (BigInt, BigInt, BigInt) { let (a, b, c) = extended_gcd(Cow::Owned(self), Cow::Borrowed(other), true); (a, b.unwrap(), c.unwrap()) } } impl<'a> ExtendedGcd<&'a BigInt> for BigUint { fn extended_gcd(self, other: &'a BigInt) -> (BigInt, BigInt, BigInt) { let (a, b, c) = extended_gcd( Cow::Owned(self), Cow::Owned(other.to_biguint().unwrap()), true, ); (a, b.unwrap(), c.unwrap()) } } impl<'a, 'b> ExtendedGcd<&'b BigInt> for &'a BigUint { fn extended_gcd(self, other: &'b BigInt) -> (BigInt, BigInt, BigInt) { let (a, b, c) = extended_gcd( Cow::Borrowed(self), Cow::Owned(other.to_biguint().unwrap()), true, ); (a, b.unwrap(), c.unwrap()) } } impl<'a, 'b> ExtendedGcd<&'b BigUint> for &'a BigUint { fn extended_gcd(self, other: &'b BigUint) -> (BigInt, BigInt, BigInt) { let (a, b, c) = extended_gcd(Cow::Borrowed(self), Cow::Borrowed(other), true); (a, b.unwrap(), c.unwrap()) } } #[test] fn test_set_digit() { let mut a = BigUint::new(vec![3]); a.set_digit(4); assert_eq!(a.data.len(), 1); assert_eq!(a.data[0], 4); let mut a = BigUint::new(vec![3, 2]); a.set_digit(4); assert_eq!(a.data.len(), 1); assert_eq!(a.data[0], 4); let mut a = BigUint::new(vec![]); a.set_digit(4); assert_eq!(a.data.len(), 1); assert_eq!(a.data[0], 4); } // arbitrary support #[cfg(feature = "fuzz")] impl arbitrary::Arbitrary<'_> for BigUint { fn arbitrary(src: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result { let data = SmallVec::arbitrary(src)?; Ok(Self { data }) } fn size_hint(depth: usize) -> (usize, Option) { SmallVec::<[BigDigit; VEC_SIZE]>::size_hint(depth) } } num-bigint-dig-0.8.2/src/lib.rs000064400000000000000000000154661046102023000143640ustar 00000000000000// Copyright 2018 Stichting Organism // // Copyright 2018 Friedel Ziegelmayer // // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A Big integer (signed version: `BigInt`, unsigned version: `BigUint`). //! //! A `BigUint` is represented as a vector of `BigDigit`s. //! A `BigInt` is a combination of `BigUint` and `Sign`. //! //! Common numerical operations are overloaded, so we can treat them //! the same way we treat other numbers. //! //! ## Example //! //! ```rust //! extern crate num_bigint_dig as num_bigint; //! extern crate num_traits; //! //! # fn main() { //! use num_bigint::BigUint; //! use num_traits::{Zero, One}; //! use std::mem::replace; //! //! // Calculate large fibonacci numbers. //! fn fib(n: usize) -> BigUint { //! let mut f0: BigUint = Zero::zero(); //! let mut f1: BigUint = One::one(); //! for _ in 0..n { //! let f2 = f0 + &f1; //! // This is a low cost way of swapping f0 with f1 and f1 with f2. //! f0 = replace(&mut f1, f2); //! } //! f0 //! } //! //! // This is a very large number. //! //println!("fib(1000) = {}", fib(1000)); //! # } //! ``` //! //! It's easy to generate large random numbers: //! #![cfg_attr(feature = "std", doc = " ```")] #![cfg_attr(not(feature = "std"), doc = " ```ignore")] //! //! # #[cfg(feature = "rand")] //! extern crate rand; //! extern crate num_bigint_dig as bigint; //! //! # #[cfg(feature = "rand")] //! # fn main() { //! use bigint::{ToBigInt, RandBigInt}; //! //! let mut rng = rand::thread_rng(); //! let a = rng.gen_bigint(1000); //! //! let low = -10000.to_bigint().unwrap(); //! let high = 10000.to_bigint().unwrap(); //! let b = rng.gen_bigint_range(&low, &high); //! //! // Probably an even larger number. //! //println!("{}", a * b); //! # } //! //! # #[cfg(not(feature = "rand"))] //! # fn main() { //! # } //! ``` //! //! ## Compatibility //! //! The `num-bigint-dig` crate is tested for rustc 1.56 and greater. //! //! ## `no_std` compatibility //! //! This crate is compatible with `no_std` environments. //! //! Note however that it still requires the `alloc` crate, so the user should //! ensure that they set a `global_allocator`. //! //! To use in no_std environment, add the crate as such in your `Cargo.toml` //! file: //! //! ```toml //! [dependencies] //! num-bigint-dig = { version = "0.8", default-features=false } //! ``` //! //! Every features should be compatible with no_std environment, so feel free to //! add features like `prime`, `i128`, etc... #![doc(html_root_url = "https://docs.rs/num-bigint/0.2")] #![no_std] extern crate alloc; #[cfg(feature = "std")] extern crate std; #[macro_use] extern crate smallvec; #[cfg(feature = "prime")] #[macro_use] extern crate lazy_static; extern crate num_integer as integer; use core::fmt; #[cfg(feature = "std")] use std::error::Error; #[macro_use] mod macros; mod bigint; mod biguint; #[cfg(feature = "prime")] pub mod prime; pub mod algorithms; pub mod traits; pub use crate::traits::*; #[cfg(feature = "rand")] mod bigrand; #[cfg(target_pointer_width = "32")] type UsizePromotion = u32; #[cfg(target_pointer_width = "64")] type UsizePromotion = u64; #[cfg(target_pointer_width = "32")] type IsizePromotion = i32; #[cfg(target_pointer_width = "64")] type IsizePromotion = i64; #[derive(Debug, Clone, PartialEq, Eq)] pub struct ParseBigIntError { kind: BigIntErrorKind, } #[derive(Debug, Clone, PartialEq, Eq)] enum BigIntErrorKind { Empty, InvalidDigit, } impl ParseBigIntError { fn __description(&self) -> &str { use crate::BigIntErrorKind::*; match self.kind { Empty => "cannot parse integer from empty string", InvalidDigit => "invalid digit found in string", } } fn empty() -> Self { ParseBigIntError { kind: BigIntErrorKind::Empty, } } fn invalid() -> Self { ParseBigIntError { kind: BigIntErrorKind::InvalidDigit, } } } impl fmt::Display for ParseBigIntError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.__description().fmt(f) } } #[cfg(feature = "std")] impl Error for ParseBigIntError { fn description(&self) -> &str { self.__description() } } pub use crate::biguint::BigUint; pub use crate::biguint::IntoBigUint; pub use crate::biguint::ToBigUint; pub use crate::bigint::negate_sign; pub use crate::bigint::BigInt; pub use crate::bigint::IntoBigInt; pub use crate::bigint::Sign; pub use crate::bigint::ToBigInt; #[cfg(feature = "rand")] pub use crate::bigrand::{RandBigInt, RandomBits, UniformBigInt, UniformBigUint}; #[cfg(feature = "prime")] pub use bigrand::RandPrime; #[cfg(not(feature = "u64_digit"))] pub const VEC_SIZE: usize = 8; #[cfg(feature = "u64_digit")] pub const VEC_SIZE: usize = 4; mod big_digit { /// A `BigDigit` is a `BigUint`'s composing element. #[cfg(not(feature = "u64_digit"))] pub type BigDigit = u32; #[cfg(feature = "u64_digit")] pub type BigDigit = u64; /// A `DoubleBigDigit` is the internal type used to do the computations. Its /// size is the double of the size of `BigDigit`. #[cfg(not(feature = "u64_digit"))] pub type DoubleBigDigit = u64; #[cfg(feature = "u64_digit")] pub type DoubleBigDigit = u128; /// A `SignedDoubleBigDigit` is the signed version of `DoubleBigDigit`. #[cfg(not(feature = "u64_digit"))] pub type SignedDoubleBigDigit = i64; #[cfg(feature = "u64_digit")] pub type SignedDoubleBigDigit = i128; // `DoubleBigDigit` size dependent #[cfg(not(feature = "u64_digit"))] pub const BITS: usize = 32; #[cfg(feature = "u64_digit")] pub const BITS: usize = 64; #[cfg(not(feature = "u64_digit"))] const LO_MASK: DoubleBigDigit = (-1i32 as DoubleBigDigit) >> BITS; #[cfg(feature = "u64_digit")] const LO_MASK: DoubleBigDigit = (-1i64 as DoubleBigDigit) >> BITS; #[inline] fn get_hi(n: DoubleBigDigit) -> BigDigit { (n >> BITS) as BigDigit } #[inline] fn get_lo(n: DoubleBigDigit) -> BigDigit { (n & LO_MASK) as BigDigit } /// Split one `DoubleBigDigit` into two `BigDigit`s. #[inline] pub fn from_doublebigdigit(n: DoubleBigDigit) -> (BigDigit, BigDigit) { (get_hi(n), get_lo(n)) } /// Join two `BigDigit`s into one `DoubleBigDigit` #[inline] pub fn to_doublebigdigit(hi: BigDigit, lo: BigDigit) -> DoubleBigDigit { (DoubleBigDigit::from(lo)) | ((DoubleBigDigit::from(hi)) << BITS) } } num-bigint-dig-0.8.2/src/macro.rs000064400000000000000000000000001046102023000146710ustar 00000000000000num-bigint-dig-0.8.2/src/macros.rs000064400000000000000000000250561046102023000150760ustar 00000000000000#![allow(unknown_lints)] // older rustc doesn't know `unused_macros` #![allow(unused_macros)] macro_rules! forward_val_val_binop { (impl $imp:ident for $res:ty, $method:ident) => { impl $imp<$res> for $res { type Output = $res; #[inline] fn $method(self, other: $res) -> $res { // forward to val-ref $imp::$method(self, &other) } } }; } macro_rules! forward_val_val_binop_commutative { (impl $imp:ident for $res:ty, $method:ident) => { impl $imp<$res> for $res { type Output = $res; #[inline] fn $method(self, other: $res) -> $res { // forward to val-ref, with the larger capacity as val if self.capacity() >= other.capacity() { $imp::$method(self, &other) } else { $imp::$method(other, &self) } } } }; } macro_rules! forward_ref_val_binop { (impl $imp:ident for $res:ty, $method:ident) => { impl<'a> $imp<$res> for &'a $res { type Output = $res; #[inline] fn $method(self, other: $res) -> $res { // forward to ref-ref $imp::$method(self, &other) } } }; } macro_rules! forward_ref_val_binop_commutative { (impl $imp:ident for $res:ty, $method:ident) => { impl<'a> $imp<$res> for &'a $res { type Output = $res; #[inline] fn $method(self, other: $res) -> $res { // reverse, forward to val-ref $imp::$method(other, self) } } }; } macro_rules! forward_val_ref_binop { (impl $imp:ident for $res:ty, $method:ident) => { impl<'a> $imp<&'a $res> for $res { type Output = $res; #[inline] fn $method(self, other: &$res) -> $res { // forward to ref-ref $imp::$method(&self, other) } } }; } macro_rules! forward_ref_ref_binop { (impl $imp:ident for $res:ty, $method:ident) => { impl<'a, 'b> $imp<&'b $res> for &'a $res { type Output = $res; #[inline] fn $method(self, other: &$res) -> $res { // forward to val-ref $imp::$method(self.clone(), other) } } }; } macro_rules! forward_ref_ref_binop_commutative { (impl $imp:ident for $res:ty, $method:ident) => { impl<'a, 'b> $imp<&'b $res> for &'a $res { type Output = $res; #[inline] fn $method(self, other: &$res) -> $res { // forward to val-ref, choosing the larger to clone if self.len() >= other.len() { $imp::$method(self.clone(), other) } else { $imp::$method(other.clone(), self) } } } }; } macro_rules! forward_val_assign { (impl $imp:ident for $res:ty, $method:ident) => { impl $imp<$res> for $res { #[inline] fn $method(&mut self, other: $res) { self.$method(&other); } } }; } macro_rules! forward_val_assign_scalar { (impl $imp:ident for $res:ty, $scalar:ty, $method:ident) => { impl $imp<$res> for $scalar { #[inline] fn $method(&mut self, other: $res) { self.$method(&other); } } }; } macro_rules! forward_scalar_val_val_binop_commutative { (impl $imp:ident < $scalar:ty > for $res:ty, $method:ident) => { impl $imp<$res> for $scalar { type Output = $res; #[inline] fn $method(self, other: $res) -> $res { $imp::$method(other, self) } } }; } macro_rules! forward_scalar_val_ref_binop { (impl $imp:ident < $scalar:ty > for $res:ty, $method:ident) => { impl<'a> $imp<&'a $scalar> for $res { type Output = $res; #[inline] fn $method(self, other: &$scalar) -> $res { $imp::$method(self, *other) } } impl<'a> $imp<$res> for &'a $scalar { type Output = $res; #[inline] fn $method(self, other: $res) -> $res { $imp::$method(*self, other) } } }; } macro_rules! forward_scalar_ref_val_binop { (impl $imp:ident < $scalar:ty > for $res:ty, $method:ident) => { impl<'a> $imp<$scalar> for &'a $res { type Output = $res; #[inline] fn $method(self, other: $scalar) -> $res { $imp::$method(self.clone(), other) } } impl<'a> $imp<&'a $res> for $scalar { type Output = $res; #[inline] fn $method(self, other: &$res) -> $res { $imp::$method(self, other.clone()) } } }; } macro_rules! forward_scalar_ref_ref_binop { (impl $imp:ident < $scalar:ty > for $res:ty, $method:ident) => { impl<'a, 'b> $imp<&'b $scalar> for &'a $res { type Output = $res; #[inline] fn $method(self, other: &$scalar) -> $res { $imp::$method(self.clone(), *other) } } impl<'a, 'b> $imp<&'a $res> for &'b $scalar { type Output = $res; #[inline] fn $method(self, other: &$res) -> $res { $imp::$method(*self, other.clone()) } } }; } macro_rules! promote_scalars { (impl $imp:ident<$promo:ty> for $res:ty, $method:ident, $( $scalar:ty ),*) => { $( forward_all_scalar_binop_to_val_val!(impl $imp<$scalar> for $res, $method); impl $imp<$scalar> for $res { type Output = $res; #[inline] fn $method(self, other: $scalar) -> $res { $imp::$method(self, other as $promo) } } impl $imp<$res> for $scalar { type Output = $res; #[inline] fn $method(self, other: $res) -> $res { $imp::$method(self as $promo, other) } } )* } } macro_rules! promote_scalars_assign { (impl $imp:ident<$promo:ty> for $res:ty, $method:ident, $( $scalar:ty ),*) => { $( impl $imp<$scalar> for $res { #[inline] fn $method(&mut self, other: $scalar) { self.$method(other as $promo); } } )* } } macro_rules! promote_unsigned_scalars { (impl $imp:ident for $res:ty, $method:ident) => { promote_scalars!(impl $imp for $res, $method, u8, u16); promote_scalars!(impl $imp for $res, $method, usize); } } macro_rules! promote_unsigned_scalars_assign { (impl $imp:ident for $res:ty, $method:ident) => { promote_scalars_assign!(impl $imp for $res, $method, u8, u16); promote_scalars_assign!(impl $imp for $res, $method, usize); } } macro_rules! promote_signed_scalars { (impl $imp:ident for $res:ty, $method:ident) => { promote_scalars!(impl $imp for $res, $method, i8, i16); promote_scalars!(impl $imp for $res, $method, isize); } } macro_rules! promote_signed_scalars_assign { (impl $imp:ident for $res:ty, $method:ident) => { promote_scalars_assign!(impl $imp for $res, $method, i8, i16); promote_scalars_assign!(impl $imp for $res, $method, isize); } } // Forward everything to ref-ref, when reusing storage is not helpful macro_rules! forward_all_binop_to_ref_ref { (impl $imp:ident for $res:ty, $method:ident) => { forward_val_val_binop!(impl $imp for $res, $method); forward_val_ref_binop!(impl $imp for $res, $method); forward_ref_val_binop!(impl $imp for $res, $method); }; } // Forward everything to val-ref, so LHS storage can be reused macro_rules! forward_all_binop_to_val_ref { (impl $imp:ident for $res:ty, $method:ident) => { forward_val_val_binop!(impl $imp for $res, $method); forward_ref_val_binop!(impl $imp for $res, $method); forward_ref_ref_binop!(impl $imp for $res, $method); }; } // Forward everything to val-ref, commutatively, so either LHS or RHS storage can be reused macro_rules! forward_all_binop_to_val_ref_commutative { (impl $imp:ident for $res:ty, $method:ident) => { forward_val_val_binop_commutative!(impl $imp for $res, $method); forward_ref_val_binop_commutative!(impl $imp for $res, $method); forward_ref_ref_binop_commutative!(impl $imp for $res, $method); }; } macro_rules! forward_all_scalar_binop_to_val_val { (impl $imp:ident<$scalar:ty> for $res:ty, $method:ident) => { forward_scalar_val_ref_binop!(impl $imp<$scalar> for $res, $method); forward_scalar_ref_val_binop!(impl $imp<$scalar> for $res, $method); forward_scalar_ref_ref_binop!(impl $imp<$scalar> for $res, $method); } } macro_rules! forward_all_scalar_binop_to_val_val_commutative { (impl $imp:ident<$scalar:ty> for $res:ty, $method:ident) => { forward_scalar_val_val_binop_commutative!(impl $imp<$scalar> for $res, $method); forward_all_scalar_binop_to_val_val!(impl $imp<$scalar> for $res, $method); } } macro_rules! promote_all_scalars { (impl $imp:ident for $res:ty, $method:ident) => { promote_unsigned_scalars!(impl $imp for $res, $method); promote_signed_scalars!(impl $imp for $res, $method); } } macro_rules! promote_all_scalars_assign { (impl $imp:ident for $res:ty, $method:ident) => { promote_unsigned_scalars_assign!(impl $imp for $res, $method); promote_signed_scalars_assign!(impl $imp for $res, $method); } } macro_rules! impl_sum_iter_type { ($res:ty) => { impl Sum for $res where $res: Add, { fn sum(iter: I) -> Self where I: Iterator, { iter.fold(Zero::zero(), <$res>::add) } } }; } macro_rules! impl_product_iter_type { ($res:ty) => { impl Product for $res where $res: Mul, { fn product(iter: I) -> Self where I: Iterator, { iter.fold(One::one(), <$res>::mul) } } }; } num-bigint-dig-0.8.2/src/monty.rs000064400000000000000000000153751046102023000147630ustar 00000000000000#![allow(clippy::many_single_char_names)] use alloc::vec::Vec; use core::ops::Shl; use num_traits::{One, Zero}; use crate::big_digit::{self, BigDigit, DoubleBigDigit, SignedDoubleBigDigit}; use crate::biguint::BigUint; struct MontyReducer { n0inv: BigDigit, } // k0 = -m**-1 mod 2**BITS. Algorithm from: Dumas, J.G. "On Newton–Raphson // Iteration for Multiplicative Inverses Modulo Prime Powers". fn inv_mod_alt(b: BigDigit) -> BigDigit { assert_ne!(b & 1, 0); let mut k0 = 2 - b as SignedDoubleBigDigit; let mut t = (b - 1) as SignedDoubleBigDigit; let mut i = 1; while i < big_digit::BITS { t = t.wrapping_mul(t); k0 = k0.wrapping_mul(t + 1); i <<= 1; } -k0 as BigDigit } impl MontyReducer { fn new(n: &BigUint) -> Self { let n0inv = inv_mod_alt(n.data[0]); MontyReducer { n0inv } } } /// Computes z mod m = x * y * 2 ** (-n*_W) mod m /// assuming k = -1/m mod 2**_W /// See Gueron, "Efficient Software Implementations of Modular Exponentiation". /// https://eprint.iacr.org/2011/239.pdf /// In the terminology of that paper, this is an "Almost Montgomery Multiplication": /// x and y are required to satisfy 0 <= z < 2**(n*_W) and then the result /// z is guaranteed to satisfy 0 <= z < 2**(n*_W), but it may not be < m. fn montgomery(z: &mut BigUint, x: &BigUint, y: &BigUint, m: &BigUint, k: BigDigit, n: usize) { // This code assumes x, y, m are all the same length, n. // (required by addMulVVW and the for loop). // It also assumes that x, y are already reduced mod m, // or else the result will not be properly reduced. assert!( x.data.len() == n && y.data.len() == n && m.data.len() == n, "{:?} {:?} {:?} {}", x, y, m, n ); z.data.clear(); z.data.resize(n * 2, 0); let mut c: BigDigit = 0; for i in 0..n { let c2 = add_mul_vvw(&mut z.data[i..n + i], &x.data, y.data[i]); let t = z.data[i].wrapping_mul(k); let c3 = add_mul_vvw(&mut z.data[i..n + i], &m.data, t); let cx = c.wrapping_add(c2); let cy = cx.wrapping_add(c3); z.data[n + i] = cy; c = if cx < c2 || cy < c3 { 1 } else { 0 }; } if c == 0 { let (first, second) = z.data.split_at_mut(n); first.swap_with_slice(&mut second[..]); } else { let (mut first, second) = z.data.split_at_mut(n); sub_vv(&mut first, &second, &m.data); } z.data.truncate(n); } #[inline] fn add_mul_vvw(z: &mut [BigDigit], x: &[BigDigit], y: BigDigit) -> BigDigit { let mut c = 0; for (zi, xi) in z.iter_mut().zip(x.iter()) { let (z1, z0) = mul_add_www(*xi, y, *zi); let (c_, zi_) = add_ww(z0, c, 0); *zi = zi_; c = c_ + z1; } c } /// The resulting carry c is either 0 or 1. #[inline] fn sub_vv(z: &mut [BigDigit], x: &[BigDigit], y: &[BigDigit]) -> BigDigit { let mut c = 0; for (i, (xi, yi)) in x.iter().zip(y.iter()).enumerate().take(z.len()) { let zi = xi.wrapping_sub(*yi).wrapping_sub(c); z[i] = zi; // see "Hacker's Delight", section 2-12 (overflow detection) c = ((yi & !xi) | ((yi | !xi) & zi)) >> (big_digit::BITS - 1) } c } /// z1<<_W + z0 = x+y+c, with c == 0 or 1 #[inline] fn add_ww(x: BigDigit, y: BigDigit, c: BigDigit) -> (BigDigit, BigDigit) { let yc = y.wrapping_add(c); let z0 = x.wrapping_add(yc); let z1 = if z0 < x || yc < y { 1 } else { 0 }; (z1, z0) } /// z1 << _W + z0 = x * y + c #[inline] fn mul_add_www(x: BigDigit, y: BigDigit, c: BigDigit) -> (BigDigit, BigDigit) { let z = x as DoubleBigDigit * y as DoubleBigDigit + c as DoubleBigDigit; ((z >> big_digit::BITS) as BigDigit, z as BigDigit) } /// Calculates x ** y mod m using a fixed, 4-bit window. pub fn monty_modpow(x: &BigUint, y: &BigUint, m: &BigUint) -> BigUint { assert!(m.data[0] & 1 == 1); let mr = MontyReducer::new(m); let num_words = m.data.len(); let mut x = x.clone(); // We want the lengths of x and m to be equal. // It is OK if x >= m as long as len(x) == len(m). if x.data.len() > num_words { x %= m; // Note: now len(x) <= numWords, not guaranteed ==. } if x.data.len() < num_words { x.data.resize(num_words, 0); } // rr = 2**(2*_W*len(m)) mod m let mut rr = BigUint::one(); rr = (rr.shl(2 * num_words * big_digit::BITS)) % m; if rr.data.len() < num_words { rr.data.resize(num_words, 0); } // one = 1, with equal length to that of m let mut one = BigUint::one(); one.data.resize(num_words, 0); let n = 4; // powers[i] contains x^i let mut powers = Vec::with_capacity(1 << n); let mut v1 = BigUint::zero(); montgomery(&mut v1, &one, &rr, m, mr.n0inv, num_words); powers.push(v1); let mut v2 = BigUint::zero(); montgomery(&mut v2, &x, &rr, m, mr.n0inv, num_words); powers.push(v2); for i in 2..1 << n { let mut r = BigUint::zero(); montgomery(&mut r, &powers[i - 1], &powers[1], m, mr.n0inv, num_words); powers.push(r); } // initialize z = 1 (Montgomery 1) let mut z = powers[0].clone(); z.data.resize(num_words, 0); let mut zz = BigUint::zero(); zz.data.resize(num_words, 0); // same windowed exponent, but with Montgomery multiplications for i in (0..y.data.len()).rev() { let mut yi = y.data[i]; let mut j = 0; while j < big_digit::BITS { if i != y.data.len() - 1 || j != 0 { montgomery(&mut zz, &z, &z, m, mr.n0inv, num_words); montgomery(&mut z, &zz, &zz, m, mr.n0inv, num_words); montgomery(&mut zz, &z, &z, m, mr.n0inv, num_words); montgomery(&mut z, &zz, &zz, m, mr.n0inv, num_words); } montgomery( &mut zz, &z, &powers[(yi >> (big_digit::BITS - n)) as usize], m, mr.n0inv, num_words, ); core::mem::swap(&mut z, &mut zz); yi <<= n; j += n; } } // convert to regular number montgomery(&mut zz, &z, &one, m, mr.n0inv, num_words); zz.normalize(); // One last reduction, just in case. // See golang.org/issue/13907. if &zz >= m { // Common case is m has high bit set; in that case, // since zz is the same length as m, there can be just // one multiple of m to remove. Just subtract. // We think that the subtract should be sufficient in general, // so do that unconditionally, but double-check, // in case our beliefs are wrong. // The div is not expected to be reached. zz -= m; if &zz >= m { zz %= m; } } zz.normalize(); zz } num-bigint-dig-0.8.2/src/prime.rs000064400000000000000000000535571046102023000147350ustar 00000000000000// https://github.com/RustCrypto/RSA/blob/master/src/prime.rs //! Implements probabilistic prime checkers. use byteorder::{BigEndian, ByteOrder}; use integer::Integer; use num_traits::{FromPrimitive, One, ToPrimitive, Zero}; use rand::rngs::StdRng; use rand::SeedableRng; use crate::algorithms::jacobi; use crate::big_digit; use crate::bigrand::RandBigInt; use crate::Sign::Plus; use crate::{BigInt, BigUint, IntoBigUint}; lazy_static! { pub(crate) static ref BIG_1: BigUint = BigUint::one(); pub(crate) static ref BIG_2: BigUint = BigUint::from_u64(2).unwrap(); pub(crate) static ref BIG_3: BigUint = BigUint::from_u64(3).unwrap(); pub(crate) static ref BIG_64: BigUint = BigUint::from_u64(64).unwrap(); } const PRIMES_A: u64 = 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23 * 37; const PRIMES_B: u64 = 29 * 31 * 41 * 43 * 47 * 53; /// Records the primes < 64. const PRIME_BIT_MASK: u64 = 1 << 2 | 1 << 3 | 1 << 5 | 1 << 7 | 1 << 11 | 1 << 13 | 1 << 17 | 1 << 19 | 1 << 23 | 1 << 29 | 1 << 31 | 1 << 37 | 1 << 41 | 1 << 43 | 1 << 47 | 1 << 53 | 1 << 59 | 1 << 61; /// ProbablyPrime reports whether x is probably prime, /// applying the Miller-Rabin test with n pseudorandomly chosen bases /// as well as a Baillie-PSW test. /// /// If x is prime, ProbablyPrime returns true. /// If x is chosen randomly and not prime, ProbablyPrime probably returns false. /// The probability of returning true for a randomly chosen non-prime is at most ¼ⁿ. /// /// ProbablyPrime is 100% accurate for inputs less than 2⁶⁴. /// See Menezes et al., Handbook of Applied Cryptography, 1997, pp. 145-149, /// and FIPS 186-4 Appendix F for further discussion of the error probabilities. /// /// ProbablyPrime is not suitable for judging primes that an adversary may /// have crafted to fool the test. /// /// This is a port of `ProbablyPrime` from the go std lib. pub fn probably_prime(x: &BigUint, n: usize) -> bool { if x.is_zero() { return false; } if x < &*BIG_64 { return (PRIME_BIT_MASK & (1 << x.to_u64().unwrap())) != 0; } if x.is_even() { return false; } let r_a = &(x % PRIMES_A); let r_b = &(x % PRIMES_B); if (r_a % 3u32).is_zero() || (r_a % 5u32).is_zero() || (r_a % 7u32).is_zero() || (r_a % 11u32).is_zero() || (r_a % 13u32).is_zero() || (r_a % 17u32).is_zero() || (r_a % 19u32).is_zero() || (r_a % 23u32).is_zero() || (r_a % 37u32).is_zero() || (r_b % 29u32).is_zero() || (r_b % 31u32).is_zero() || (r_b % 41u32).is_zero() || (r_b % 43u32).is_zero() || (r_b % 47u32).is_zero() || (r_b % 53u32).is_zero() { return false; } probably_prime_miller_rabin(x, n + 1, true) && probably_prime_lucas(x) } const NUMBER_OF_PRIMES: usize = 127; const PRIME_GAP: [u64; 167] = [ 2, 2, 4, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4, 2, 4, 14, 4, 6, 2, 10, 2, 6, 6, 4, 6, 6, 2, 10, 2, 4, 2, 12, 12, 4, 2, 4, 6, 2, 10, 6, 6, 6, 2, 6, 4, 2, 10, 14, 4, 2, 4, 14, 6, 10, 2, 4, 6, 8, 6, 6, 4, 6, 8, 4, 8, 10, 2, 10, 2, 6, 4, 6, 8, 4, 2, 4, 12, 8, 4, 8, 4, 6, 12, 2, 18, 6, 10, 6, 6, 2, 6, 10, 6, 6, 2, 6, 6, 4, 2, 12, 10, 2, 4, 6, 6, 2, 12, 4, 6, 8, 10, 8, 10, 8, 6, 6, 4, 8, 6, 4, 8, 4, 14, 10, 12, 2, 10, 2, 4, 2, 10, 14, 4, 2, 4, 14, 4, 2, 4, 20, 4, 8, 10, 8, 4, 6, 6, 14, 4, 6, 6, 8, 6, 12, ]; const INCR_LIMIT: usize = 0x10000; /// Calculate the next larger prime, given a starting number `n`. pub fn next_prime(n: &BigUint) -> BigUint { if n < &*BIG_2 { return 2u32.into_biguint().unwrap(); } // We want something larger than our current number. let mut res = n + &*BIG_1; // Ensure we are odd. res |= &*BIG_1; // Handle values up to 7. if let Some(val) = res.to_u64() { if val < 7 { return res; } } let nbits = res.bits(); let prime_limit = if nbits / 2 >= NUMBER_OF_PRIMES { NUMBER_OF_PRIMES - 1 } else { nbits / 2 }; // Compute the residues modulo small odd primes let mut moduli = vec![BigUint::zero(); prime_limit]; 'outer: loop { let mut prime = 3; for i in 0..prime_limit { moduli[i] = &res / prime; prime += PRIME_GAP[i]; } // Check residues let mut difference: usize = 0; for incr in (0..INCR_LIMIT as u64).step_by(2) { let mut prime: u64 = 3; let mut cancel = false; for i in 0..prime_limit { let r = (&moduli[i] + incr) % prime; prime += PRIME_GAP[i]; if r.is_zero() { cancel = true; break; } } if !cancel { res += difference; difference = 0; if probably_prime(&res, 20) { break 'outer; } } difference += 2; } res += difference; } res } /// Reports whether n passes reps rounds of the Miller-Rabin primality test, using pseudo-randomly chosen bases. /// If `force2` is true, one of the rounds is forced to use base 2. /// /// See Handbook of Applied Cryptography, p. 139, Algorithm 4.24. pub fn probably_prime_miller_rabin(n: &BigUint, reps: usize, force2: bool) -> bool { // println!("miller-rabin: {}", n); let nm1 = n - &*BIG_1; // determine q, k such that nm1 = q << k let k = nm1.trailing_zeros().unwrap() as usize; let q = &nm1 >> k; let nm3 = n - &*BIG_3; let mut seed_vec = vec![0u8; 8]; BigEndian::write_uint( seed_vec.as_mut_slice(), n.get_limb(0) as u64, big_digit::BITS / 8, ); let mut seed = [0u8; 32]; seed[0..8].copy_from_slice(&seed_vec[..]); let mut rng = StdRng::from_seed(seed); 'nextrandom: for i in 0..reps { let x = if i == reps - 1 && force2 { BIG_2.clone() } else { rng.gen_biguint_below(&nm3) + &*BIG_2 }; let mut y = x.modpow(&q, n); if y.is_one() || y == nm1 { continue; } for _ in 1..k { y = y.modpow(&*BIG_2, n); if y == nm1 { break 'nextrandom; } if y.is_one() { return false; } } return false; } true } /// Reports whether n passes the "almost extra strong" Lucas probable prime test, /// using Baillie-OEIS parameter selection. This corresponds to "AESLPSP" on Jacobsen's tables (link below). /// The combination of this test and a Miller-Rabin/Fermat test with base 2 gives a Baillie-PSW test. /// /// /// References: /// /// Baillie and Wagstaff, "Lucas Pseudoprimes", Mathematics of Computation 35(152), /// October 1980, pp. 1391-1417, especially page 1401. /// http://www.ams.org/journals/mcom/1980-35-152/S0025-5718-1980-0583518-6/S0025-5718-1980-0583518-6.pdf /// /// Grantham, "Frobenius Pseudoprimes", Mathematics of Computation 70(234), /// March 2000, pp. 873-891. /// http://www.ams.org/journals/mcom/2001-70-234/S0025-5718-00-01197-2/S0025-5718-00-01197-2.pdf /// /// Baillie, "Extra strong Lucas pseudoprimes", OEIS A217719, https://oeis.org/A217719. /// /// Jacobsen, "Pseudoprime Statistics, Tables, and Data", http://ntheory.org/pseudoprimes.html. /// /// Nicely, "The Baillie-PSW Primality Test", http://www.trnicely.net/misc/bpsw.html. /// (Note that Nicely's definition of the "extra strong" test gives the wrong Jacobi condition, /// as pointed out by Jacobsen.) /// /// Crandall and Pomerance, Prime Numbers: A Computational Perspective, 2nd ed. /// Springer, 2005. pub fn probably_prime_lucas(n: &BigUint) -> bool { // println!("lucas: {}", n); // Discard 0, 1. if n.is_zero() || n.is_one() { return false; } // Two is the only even prime. if n.to_u64() == Some(2) { return false; } // Baillie-OEIS "method C" for choosing D, P, Q, // as in https://oeis.org/A217719/a217719.txt: // try increasing P ≥ 3 such that D = P² - 4 (so Q = 1) // until Jacobi(D, n) = -1. // The search is expected to succeed for non-square n after just a few trials. // After more than expected failures, check whether n is square // (which would cause Jacobi(D, n) = 1 for all D not dividing n). let mut p = 3u64; let n_int = BigInt::from_biguint(Plus, n.clone()); loop { if p > 10000 { // This is widely believed to be impossible. // If we get a report, we'll want the exact number n. panic!("internal error: cannot find (D/n) = -1 for {:?}", n) } let j = jacobi(&BigInt::from_u64(p * p - 4).unwrap(), &n_int); if j == -1 { break; } if j == 0 { // d = p²-4 = (p-2)(p+2). // If (d/n) == 0 then d shares a prime factor with n. // Since the loop proceeds in increasing p and starts with p-2==1, // the shared prime factor must be p+2. // If p+2 == n, then n is prime; otherwise p+2 is a proper factor of n. return n_int.to_i64() == Some(p as i64 + 2); } // We'll never find (d/n) = -1 if n is a square. // If n is a non-square we expect to find a d in just a few attempts on average. // After 40 attempts, take a moment to check if n is indeed a square. let t1 = &n_int * &n_int; if p == 40 && t1.sqrt() == n_int { return false; } p += 1; } // Grantham definition of "extra strong Lucas pseudoprime", after Thm 2.3 on p. 876 // (D, P, Q above have become Δ, b, 1): // // Let U_n = U_n(b, 1), V_n = V_n(b, 1), and Δ = b²-4. // An extra strong Lucas pseudoprime to base b is a composite n = 2^r s + Jacobi(Δ, n), // where s is odd and gcd(n, 2*Δ) = 1, such that either (i) U_s ≡ 0 mod n and V_s ≡ ±2 mod n, // or (ii) V_{2^t s} ≡ 0 mod n for some 0 ≤ t < r-1. // // We know gcd(n, Δ) = 1 or else we'd have found Jacobi(d, n) == 0 above. // We know gcd(n, 2) = 1 because n is odd. // // Arrange s = (n - Jacobi(Δ, n)) / 2^r = (n+1) / 2^r. let mut s = n + &*BIG_1; let r = s.trailing_zeros().unwrap() as usize; s = &s >> r; let nm2 = n - &*BIG_2; // n - 2 // We apply the "almost extra strong" test, which checks the above conditions // except for U_s ≡ 0 mod n, which allows us to avoid computing any U_k values. // Jacobsen points out that maybe we should just do the full extra strong test: // "It is also possible to recover U_n using Crandall and Pomerance equation 3.13: // U_n = D^-1 (2V_{n+1} - PV_n) allowing us to run the full extra-strong test // at the cost of a single modular inversion. This computation is easy and fast in GMP, // so we can get the full extra-strong test at essentially the same performance as the // almost extra strong test." // Compute Lucas sequence V_s(b, 1), where: // // V(0) = 2 // V(1) = P // V(k) = P V(k-1) - Q V(k-2). // // (Remember that due to method C above, P = b, Q = 1.) // // In general V(k) = α^k + β^k, where α and β are roots of x² - Px + Q. // Crandall and Pomerance (p.147) observe that for 0 ≤ j ≤ k, // // V(j+k) = V(j)V(k) - V(k-j). // // So in particular, to quickly double the subscript: // // V(2k) = V(k)² - 2 // V(2k+1) = V(k) V(k+1) - P // // We can therefore start with k=0 and build up to k=s in log₂(s) steps. let mut vk = BIG_2.clone(); let mut vk1 = BigUint::from_u64(p).unwrap(); for i in (0..s.bits()).rev() { if is_bit_set(&s, i) { // k' = 2k+1 // V(k') = V(2k+1) = V(k) V(k+1) - P let t1 = (&vk * &vk1) + n - p; vk = &t1 % n; // V(k'+1) = V(2k+2) = V(k+1)² - 2 let t1 = (&vk1 * &vk1) + &nm2; vk1 = &t1 % n; } else { // k' = 2k // V(k'+1) = V(2k+1) = V(k) V(k+1) - P let t1 = (&vk * &vk1) + n - p; vk1 = &t1 % n; // V(k') = V(2k) = V(k)² - 2 let t1 = (&vk * &vk) + &nm2; vk = &t1 % n; } } // Now k=s, so vk = V(s). Check V(s) ≡ ±2 (mod n). if vk.to_u64() == Some(2) || vk == nm2 { // Check U(s) ≡ 0. // As suggested by Jacobsen, apply Crandall and Pomerance equation 3.13: // // U(k) = D⁻¹ (2 V(k+1) - P V(k)) // // Since we are checking for U(k) == 0 it suffices to check 2 V(k+1) == P V(k) mod n, // or P V(k) - 2 V(k+1) == 0 mod n. let mut t1 = &vk * p; let mut t2 = &vk1 << 1; if t1 < t2 { core::mem::swap(&mut t1, &mut t2); } t1 -= t2; if (t1 % n).is_zero() { return true; } } // Check V(2^t s) ≡ 0 mod n for some 0 ≤ t < r-1. for _ in 0..r - 1 { if vk.is_zero() { return true; } // Optimization: V(k) = 2 is a fixed point for V(k') = V(k)² - 2, // so if V(k) = 2, we can stop: we will never find a future V(k) == 0. if vk.to_u64() == Some(2) { return false; } // k' = 2k // V(k') = V(2k) = V(k)² - 2 let t1 = (&vk * &vk) - &*BIG_2; vk = &t1 % n; } false } /// Checks if the i-th bit is set #[inline] fn is_bit_set(x: &BigUint, i: usize) -> bool { get_bit(x, i) == 1 } /// Returns the i-th bit. #[inline] fn get_bit(x: &BigUint, i: usize) -> u8 { let j = i / big_digit::BITS; // if is out of range of the set words, it is always false. if i >= x.bits() { return 0; } (x.get_limb(j) >> (i % big_digit::BITS) & 1) as u8 } #[cfg(test)] mod tests { use super::*; use alloc::vec::Vec; // use RandBigInt; use crate::biguint::ToBigUint; lazy_static! { static ref PRIMES: Vec<&'static str> = vec![ "2", "3", "5", "7", "11", "13756265695458089029", "13496181268022124907", "10953742525620032441", "17908251027575790097", // https://golang.org/issue/638 "18699199384836356663", "98920366548084643601728869055592650835572950932266967461790948584315647051443", "94560208308847015747498523884063394671606671904944666360068158221458669711639", // http://primes.utm.edu/lists/small/small3.html "449417999055441493994709297093108513015373787049558499205492347871729927573118262811508386655998299074566974373711472560655026288668094291699357843464363003144674940345912431129144354948751003607115263071543163", "230975859993204150666423538988557839555560243929065415434980904258310530753006723857139742334640122533598517597674807096648905501653461687601339782814316124971547968912893214002992086353183070342498989426570593", "5521712099665906221540423207019333379125265462121169655563495403888449493493629943498064604536961775110765377745550377067893607246020694972959780839151452457728855382113555867743022746090187341871655890805971735385789993", "203956878356401977405765866929034577280193993314348263094772646453283062722701277632936616063144088173312372882677123879538709400158306567338328279154499698366071906766440037074217117805690872792848149112022286332144876183376326512083574821647933992961249917319836219304274280243803104015000563790123", // ECC primes: http://tools.ietf.org/html/draft-ladd-safecurves-02 "3618502788666131106986593281521497120414687020801267626233049500247285301239", // Curve1174: 2^251-9 "57896044618658097711785492504343953926634992332820282019728792003956564819949", // Curve25519: 2^255-19 "9850501549098619803069760025035903451269934817616361666987073351061430442874302652853566563721228910201656997576599", // E-382: 2^382-105 "42307582002575910332922579714097346549017899709713998034217522897561970639123926132812109468141778230245837569601494931472367", // Curve41417: 2^414-17 "6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151", // E-521: 2^521-1 ]; static ref COMPOSITES: Vec<&'static str> = vec![ "0", "1", "21284175091214687912771199898307297748211672914763848041968395774954376176754", "6084766654921918907427900243509372380954290099172559290432744450051395395951", "84594350493221918389213352992032324280367711247940675652888030554255915464401", "82793403787388584738507275144194252681", // Arnault, "Rabin-Miller Primality Test: Composite Numbers Which Pass It", // Mathematics of Computation, 64(209) (January 1995), pp. 335-361. "1195068768795265792518361315725116351898245581", // strong pseudoprime to prime bases 2 through 29 // strong pseudoprime to all prime bases up to 200 "8038374574536394912570796143419421081388376882875581458374889175222974273765333652186502336163960045457915042023603208766569966760987284043965408232928738791850869166857328267761771029389697739470167082304286871099974399765441448453411558724506334092790222752962294149842306881685404326457534018329786111298960644845216191652872597534901", // Extra-strong Lucas pseudoprimes. https://oeis.org/A217719 "989", "3239", "5777", "10877", "27971", "29681", "30739", "31631", "39059", "72389", "73919", "75077", "100127", "113573", "125249", "137549", "137801", "153931", "155819", "161027", "162133", "189419", "218321", "231703", "249331", "370229", "429479", "430127", "459191", "473891", "480689", "600059", "621781", "632249", "635627", "3673744903", "3281593591", "2385076987", "2738053141", "2009621503", "1502682721", "255866131", "117987841", "587861", "6368689", "8725753", "80579735209", "105919633", ]; } #[test] fn test_primes() { for prime in PRIMES.iter() { let p = BigUint::parse_bytes(prime.as_bytes(), 10).unwrap(); for i in [0, 1, 20].iter() { assert!( probably_prime(&p, *i as usize), "{} is a prime ({})", prime, i, ); } } } #[test] fn test_composites() { for comp in COMPOSITES.iter() { let p = BigUint::parse_bytes(comp.as_bytes(), 10).unwrap(); for i in [0, 1, 20].iter() { assert!( !probably_prime(&p, *i as usize), "{} is a composite ({})", comp, i, ); } } } macro_rules! test_pseudo_primes { ($name:ident, $cond:expr, $want:expr) => { #[test] fn $name() { let mut i = 3; let mut want = $want; while i < 100000 { let n = BigUint::from_u64(i).unwrap(); let pseudo = $cond(&n); if pseudo && (want.is_empty() || i != want[0]) { panic!("cond({}) = true, want false", i); } else if !pseudo && !want.is_empty() && i == want[0] { panic!("cond({}) = false, want true", i); } if !want.is_empty() && i == want[0] { want = want[1..].to_vec(); } i += 2; } if !want.is_empty() { panic!("forgot to test: {:?}", want); } } }; } test_pseudo_primes!( test_probably_prime_miller_rabin, |n| probably_prime_miller_rabin(n, 1, true) && !probably_prime_lucas(n), vec![ 2047, 3277, 4033, 4681, 8321, 15841, 29341, 42799, 49141, 52633, 65281, 74665, 80581, 85489, 88357, 90751, ] ); test_pseudo_primes!( test_probably_prime_lucas, |n| probably_prime_lucas(n) && !probably_prime_miller_rabin(n, 1, true), vec![989, 3239, 5777, 10877, 27971, 29681, 30739, 31631, 39059, 72389, 73919, 75077,] ); #[test] fn test_bit_set() { let v = &vec![0b10101001]; let num = BigUint::from_slice(&v); assert!(is_bit_set(&num, 0)); assert!(!is_bit_set(&num, 1)); assert!(!is_bit_set(&num, 2)); assert!(is_bit_set(&num, 3)); assert!(!is_bit_set(&num, 4)); assert!(is_bit_set(&num, 5)); assert!(!is_bit_set(&num, 6)); assert!(is_bit_set(&num, 7)); } #[test] fn test_next_prime() { let primes1 = (0..2048u32) .map(|i| next_prime(&i.to_biguint().unwrap())) .collect::>(); let primes2 = (0..2048u32) .map(|i| { let i = i.to_biguint().unwrap(); let p = next_prime(&i); assert!(&p > &i); p }) .collect::>(); for (p1, p2) in primes1.iter().zip(&primes2) { assert_eq!(p1, p2); assert!(probably_prime(p1, 25)); } } } num-bigint-dig-0.8.2/src/traits.rs000064400000000000000000000015271046102023000151150ustar 00000000000000use crate::BigInt; /// Generic trait to implement modular inverse. pub trait ModInverse: Sized { type Output: Sized; /// Function to calculate the [modular multiplicative /// inverse](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse) of an integer *a* modulo *m*. /// /// TODO: references /// Returns the modular inverse of `self`. /// If none exists it returns `None`. fn mod_inverse(self, m: R) -> Option; } /// Generic trait to implement extended GCD. /// Calculates the extended eucledian algorithm. /// See https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm for details. /// The returned values are /// - greatest common divisor (1) /// - Bezout coefficients (2) pub trait ExtendedGcd: Sized { fn extended_gcd(self, other: R) -> (BigInt, BigInt, BigInt); } num-bigint-dig-0.8.2/tests/bigint.rs000064400000000000000000001136041046102023000154360ustar 00000000000000extern crate num_bigint_dig as num_bigint; extern crate num_integer; extern crate num_traits; #[cfg(feature = "rand")] extern crate rand; use crate::num_bigint::BigUint; use crate::num_bigint::Sign::{Minus, NoSign, Plus}; use crate::num_bigint::{BigInt, ToBigInt}; use std::cmp::Ordering::{Equal, Greater, Less}; use std::collections::hash_map::RandomState; use std::hash::{BuildHasher, Hash, Hasher}; use std::iter::repeat; use std::ops::Neg; use std::{f32, f64}; #[cfg(has_i128)] use std::{i128, u128}; use std::{i16, i32, i64, i8, isize}; use std::{u16, u32, u64, u8, usize}; use num_integer::Integer; use num_traits::float::FloatCore; use num_traits::{FromPrimitive, Num, One, Pow, Signed, ToPrimitive, Zero}; mod consts; use crate::consts::*; #[macro_use] mod macros; #[test] fn test_from_bytes_be() { fn check(s: &str, result: &str) { assert_eq!( BigInt::from_bytes_be(Plus, s.as_bytes()), BigInt::parse_bytes(result.as_bytes(), 10).unwrap() ); } check("A", "65"); check("AA", "16705"); check("AB", "16706"); check("Hello world!", "22405534230753963835153736737"); assert_eq!(BigInt::from_bytes_be(Plus, &[]), Zero::zero()); assert_eq!(BigInt::from_bytes_be(Minus, &[]), Zero::zero()); } #[test] fn test_to_bytes_be() { fn check(s: &str, result: &str) { let b = BigInt::parse_bytes(result.as_bytes(), 10).unwrap(); let (sign, v) = b.to_bytes_be(); assert_eq!((Plus, s.as_bytes()), (sign, &*v)); } check("A", "65"); check("AA", "16705"); check("AB", "16706"); check("Hello world!", "22405534230753963835153736737"); let b: BigInt = Zero::zero(); assert_eq!(b.to_bytes_be(), (NoSign, vec![0])); // Test with leading/trailing zero bytes and a full BigDigit of value 0 let b = BigInt::from_str_radix("00010000000000000200", 16).unwrap(); assert_eq!(b.to_bytes_be(), (Plus, vec![1, 0, 0, 0, 0, 0, 0, 2, 0])); } #[test] fn test_from_bytes_le() { fn check(s: &str, result: &str) { assert_eq!( BigInt::from_bytes_le(Plus, s.as_bytes()), BigInt::parse_bytes(result.as_bytes(), 10).unwrap() ); } check("A", "65"); check("AA", "16705"); check("BA", "16706"); check("!dlrow olleH", "22405534230753963835153736737"); assert_eq!(BigInt::from_bytes_le(Plus, &[]), Zero::zero()); assert_eq!(BigInt::from_bytes_le(Minus, &[]), Zero::zero()); } #[test] fn test_to_bytes_le() { fn check(s: &str, result: &str) { let b = BigInt::parse_bytes(result.as_bytes(), 10).unwrap(); let (sign, v) = b.to_bytes_le(); assert_eq!((Plus, s.as_bytes()), (sign, &*v)); } check("A", "65"); check("AA", "16705"); check("BA", "16706"); check("!dlrow olleH", "22405534230753963835153736737"); let b: BigInt = Zero::zero(); assert_eq!(b.to_bytes_le(), (NoSign, vec![0])); // Test with leading/trailing zero bytes and a full BigDigit of value 0 let b = BigInt::from_str_radix("00010000000000000200", 16).unwrap(); assert_eq!(b.to_bytes_le(), (Plus, vec![0, 2, 0, 0, 0, 0, 0, 0, 1])); } #[test] fn test_to_signed_bytes_le() { fn check(s: &str, result: Vec) { assert_eq!( BigInt::parse_bytes(s.as_bytes(), 10) .unwrap() .to_signed_bytes_le(), result ); } check("0", vec![0]); check("32767", vec![0xff, 0x7f]); check("-1", vec![0xff]); check("16777216", vec![0, 0, 0, 1]); check("-100", vec![156]); check("-8388608", vec![0, 0, 0x80]); check("-192", vec![0x40, 0xff]); check("128", vec![0x80, 0]) } #[test] fn test_from_signed_bytes_le() { fn check(s: &[u8], result: &str) { assert_eq!( BigInt::from_signed_bytes_le(s), BigInt::parse_bytes(result.as_bytes(), 10).unwrap() ); } check(&[], "0"); check(&[0], "0"); check(&[0; 10], "0"); check(&[0xff, 0x7f], "32767"); check(&[0xff], "-1"); check(&[0, 0, 0, 1], "16777216"); check(&[156], "-100"); check(&[0, 0, 0x80], "-8388608"); check(&[0xff; 10], "-1"); check(&[0x40, 0xff], "-192"); } #[test] fn test_to_signed_bytes_be() { fn check(s: &str, result: Vec) { assert_eq!( BigInt::parse_bytes(s.as_bytes(), 10) .unwrap() .to_signed_bytes_be(), result ); } check("0", vec![0]); check("32767", vec![0x7f, 0xff]); check("-1", vec![255]); check("16777216", vec![1, 0, 0, 0]); check("-100", vec![156]); check("-8388608", vec![128, 0, 0]); check("-192", vec![0xff, 0x40]); check("128", vec![0, 0x80]); } #[test] fn test_from_signed_bytes_be() { fn check(s: &[u8], result: &str) { assert_eq!( BigInt::from_signed_bytes_be(s), BigInt::parse_bytes(result.as_bytes(), 10).unwrap() ); } check(&[], "0"); check(&[0], "0"); check(&[0; 10], "0"); check(&[127, 255], "32767"); check(&[255], "-1"); check(&[1, 0, 0, 0], "16777216"); check(&[156], "-100"); check(&[128, 0, 0], "-8388608"); check(&[255; 10], "-1"); check(&[0xff, 0x40], "-192"); } #[test] fn test_signed_bytes_be_round_trip() { for i in -0x1FFFF..0x20000 { let n = BigInt::from(i); assert_eq!(n, BigInt::from_signed_bytes_be(&n.to_signed_bytes_be())); } } #[test] fn test_signed_bytes_le_round_trip() { for i in -0x1FFFF..0x20000 { let n = BigInt::from(i); assert_eq!(n, BigInt::from_signed_bytes_le(&n.to_signed_bytes_le())); } } #[test] fn test_cmp() { let vs: [&[u32]; 4] = [&[2 as u32], &[1, 1], &[2, 1], &[1, 1, 1]]; let mut nums = Vec::new(); for s in vs.iter().rev() { nums.push(BigInt::from_slice(Minus, *s)); } nums.push(Zero::zero()); nums.extend(vs.iter().map(|s| BigInt::from_slice(Plus, *s))); for (i, ni) in nums.iter().enumerate() { for (j0, nj) in nums[i..].iter().enumerate() { let j = i + j0; if i == j { assert_eq!(ni.cmp(nj), Equal); assert_eq!(nj.cmp(ni), Equal); assert_eq!(ni, nj); assert!(!(ni != nj)); assert!(ni <= nj); assert!(ni >= nj); assert!(!(ni < nj)); assert!(!(ni > nj)); } else { assert_eq!(ni.cmp(nj), Less); assert_eq!(nj.cmp(ni), Greater); assert!(!(ni == nj)); assert!(ni != nj); assert!(ni <= nj); assert!(!(ni >= nj)); assert!(ni < nj); assert!(!(ni > nj)); assert!(!(nj <= ni)); assert!(nj >= ni); assert!(!(nj < ni)); assert!(nj > ni); } } } } fn hash(x: &T) -> u64 { let mut hasher = ::Hasher::new(); x.hash(&mut hasher); hasher.finish() } #[test] fn test_hash() { let a = BigInt::new(NoSign, vec![]); let b = BigInt::new(NoSign, vec![0]); let c = BigInt::new(Plus, vec![1]); let d = BigInt::new(Plus, vec![1, 0, 0, 0, 0, 0]); let e = BigInt::new(Plus, vec![0, 0, 0, 0, 0, 1]); let f = BigInt::new(Minus, vec![1]); assert!(hash(&a) == hash(&b)); assert!(hash(&b) != hash(&c)); assert!(hash(&c) == hash(&d)); assert!(hash(&d) != hash(&e)); assert!(hash(&c) != hash(&f)); } #[test] fn test_convert_i64() { fn check(b1: BigInt, i: i64) { let b2: BigInt = FromPrimitive::from_i64(i).unwrap(); assert!(b1 == b2); assert!(b1.to_i64().unwrap() == i); } check(Zero::zero(), 0); check(One::one(), 1); check(i64::MIN.to_bigint().unwrap(), i64::MIN); check(i64::MAX.to_bigint().unwrap(), i64::MAX); assert_eq!((i64::MAX as u64 + 1).to_bigint().unwrap().to_i64(), None); assert_eq!( BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3, 4, 5])).to_i64(), None ); assert_eq!( BigInt::from_biguint(Minus, BigUint::new(vec![1, 0, 0, 1 << 31])).to_i64(), None ); assert_eq!( BigInt::from_biguint(Minus, BigUint::new(vec![1, 2, 3, 4, 5])).to_i64(), None ); } #[test] #[cfg(has_i128)] fn test_convert_i128() { fn check(b1: BigInt, i: i128) { let b2: BigInt = FromPrimitive::from_i128(i).unwrap(); assert!(b1 == b2); assert!(b1.to_i128().unwrap() == i); } check(Zero::zero(), 0); check(One::one(), 1); check(i128::MIN.to_bigint().unwrap(), i128::MIN); check(i128::MAX.to_bigint().unwrap(), i128::MAX); assert_eq!((i128::MAX as u128 + 1).to_bigint().unwrap().to_i128(), None); assert_eq!( BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3, 4, 5])).to_i128(), None ); assert_eq!( BigInt::from_biguint(Minus, BigUint::new(vec![1, 0, 0, 1 << 31])).to_i128(), None ); assert_eq!( BigInt::from_biguint(Minus, BigUint::new(vec![1, 2, 3, 4, 5])).to_i128(), None ); } #[test] fn test_convert_u64() { fn check(b1: BigInt, u: u64) { let b2: BigInt = FromPrimitive::from_u64(u).unwrap(); assert!(b1 == b2); assert!(b1.to_u64().unwrap() == u); } check(Zero::zero(), 0); check(One::one(), 1); check(u64::MIN.to_bigint().unwrap(), u64::MIN); check(u64::MAX.to_bigint().unwrap(), u64::MAX); assert_eq!( BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3, 4, 5])).to_u64(), None ); let max_value: BigUint = FromPrimitive::from_u64(u64::MAX).unwrap(); assert_eq!(BigInt::from_biguint(Minus, max_value).to_u64(), None); assert_eq!( BigInt::from_biguint(Minus, BigUint::new(vec![1, 2, 3, 4, 5])).to_u64(), None ); } #[test] #[cfg(has_i128)] fn test_convert_u128() { fn check(b1: BigInt, u: u128) { let b2: BigInt = FromPrimitive::from_u128(u).unwrap(); assert!(b1 == b2); assert!(b1.to_u128().unwrap() == u); } check(Zero::zero(), 0); check(One::one(), 1); check(u128::MIN.to_bigint().unwrap(), u128::MIN); check(u128::MAX.to_bigint().unwrap(), u128::MAX); assert_eq!( BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3, 4, 5])).to_u128(), None ); let max_value: BigUint = FromPrimitive::from_u128(u128::MAX).unwrap(); assert_eq!(BigInt::from_biguint(Minus, max_value).to_u128(), None); assert_eq!( BigInt::from_biguint(Minus, BigUint::new(vec![1, 2, 3, 4, 5])).to_u128(), None ); } #[test] fn test_convert_f32() { fn check(b1: &BigInt, f: f32) { let b2 = BigInt::from_f32(f).unwrap(); assert_eq!(b1, &b2); assert_eq!(b1.to_f32().unwrap(), f); let neg_b1 = -b1; let neg_b2 = BigInt::from_f32(-f).unwrap(); assert_eq!(neg_b1, neg_b2); assert_eq!(neg_b1.to_f32().unwrap(), -f); } check(&BigInt::zero(), 0.0); check(&BigInt::one(), 1.0); check(&BigInt::from(u16::MAX), 2.0.powi(16) - 1.0); check(&BigInt::from(1u64 << 32), 2.0.powi(32)); check(&BigInt::from_slice(Plus, &[0, 0, 1]), 2.0.powi(64)); check( &((BigInt::one() << 100) + (BigInt::one() << 123)), 2.0.powi(100) + 2.0.powi(123), ); check(&(BigInt::one() << 127), 2.0.powi(127)); check(&(BigInt::from((1u64 << 24) - 1) << (128 - 24)), f32::MAX); // keeping all 24 digits with the bits at different offsets to the BigDigits let x: u32 = 0b00000000101111011111011011011101; let mut f = x as f32; let mut b = BigInt::from(x); for _ in 0..64 { check(&b, f); f *= 2.0; b = b << 1; } // this number when rounded to f64 then f32 isn't the same as when rounded straight to f32 let mut n: i64 = 0b0000000000111111111111111111111111011111111111111111111111111111; assert!((n as f64) as f32 != n as f32); assert_eq!(BigInt::from(n).to_f32(), Some(n as f32)); n = -n; assert!((n as f64) as f32 != n as f32); assert_eq!(BigInt::from(n).to_f32(), Some(n as f32)); // test rounding up with the bits at different offsets to the BigDigits let mut f = ((1u64 << 25) - 1) as f32; let mut b = BigInt::from(1u64 << 25); for _ in 0..64 { assert_eq!(b.to_f32(), Some(f)); f *= 2.0; b = b << 1; } // rounding assert_eq!( BigInt::from_f32(-f32::consts::PI), Some(BigInt::from(-3i32)) ); assert_eq!(BigInt::from_f32(-f32::consts::E), Some(BigInt::from(-2i32))); assert_eq!(BigInt::from_f32(-0.99999), Some(BigInt::zero())); assert_eq!(BigInt::from_f32(-0.5), Some(BigInt::zero())); assert_eq!(BigInt::from_f32(-0.0), Some(BigInt::zero())); assert_eq!( BigInt::from_f32(f32::MIN_POSITIVE / 2.0), Some(BigInt::zero()) ); assert_eq!(BigInt::from_f32(f32::MIN_POSITIVE), Some(BigInt::zero())); assert_eq!(BigInt::from_f32(0.5), Some(BigInt::zero())); assert_eq!(BigInt::from_f32(0.99999), Some(BigInt::zero())); assert_eq!(BigInt::from_f32(f32::consts::E), Some(BigInt::from(2u32))); assert_eq!(BigInt::from_f32(f32::consts::PI), Some(BigInt::from(3u32))); // special float values assert_eq!(BigInt::from_f32(f32::NAN), None); assert_eq!(BigInt::from_f32(f32::INFINITY), None); assert_eq!(BigInt::from_f32(f32::NEG_INFINITY), None); // largest BigInt that will round to a finite f32 value let big_num = (BigInt::one() << 128) - BigInt::one() - (BigInt::one() << (128 - 25)); assert_eq!(big_num.to_f32(), Some(f32::MAX)); assert_eq!((&big_num + BigInt::one()).to_f32(), None); assert_eq!((-&big_num).to_f32(), Some(f32::MIN)); assert_eq!(((-&big_num) - BigInt::one()).to_f32(), None); assert_eq!(((BigInt::one() << 128) - BigInt::one()).to_f32(), None); assert_eq!((BigInt::one() << 128).to_f32(), None); assert_eq!((-((BigInt::one() << 128) - BigInt::one())).to_f32(), None); assert_eq!((-(BigInt::one() << 128)).to_f32(), None); } #[test] fn test_convert_f64() { fn check(b1: &BigInt, f: f64) { let b2 = BigInt::from_f64(f).unwrap(); assert_eq!(b1, &b2); assert_eq!(b1.to_f64().unwrap(), f); let neg_b1 = -b1; let neg_b2 = BigInt::from_f64(-f).unwrap(); assert_eq!(neg_b1, neg_b2); assert_eq!(neg_b1.to_f64().unwrap(), -f); } check(&BigInt::zero(), 0.0); check(&BigInt::one(), 1.0); check(&BigInt::from(u32::MAX), 2.0.powi(32) - 1.0); check(&BigInt::from(1u64 << 32), 2.0.powi(32)); check(&BigInt::from_slice(Plus, &[0, 0, 1]), 2.0.powi(64)); check( &((BigInt::one() << 100) + (BigInt::one() << 152)), 2.0.powi(100) + 2.0.powi(152), ); check(&(BigInt::one() << 1023), 2.0.powi(1023)); check(&(BigInt::from((1u64 << 53) - 1) << (1024 - 53)), f64::MAX); // keeping all 53 digits with the bits at different offsets to the BigDigits let x: u64 = 0b0000000000011110111110110111111101110111101111011111011011011101; let mut f = x as f64; let mut b = BigInt::from(x); for _ in 0..128 { check(&b, f); f *= 2.0; b = b << 1; } // test rounding up with the bits at different offsets to the BigDigits let mut f = ((1u64 << 54) - 1) as f64; let mut b = BigInt::from(1u64 << 54); for _ in 0..128 { assert_eq!(b.to_f64(), Some(f)); f *= 2.0; b = b << 1; } // rounding assert_eq!( BigInt::from_f64(-f64::consts::PI), Some(BigInt::from(-3i32)) ); assert_eq!(BigInt::from_f64(-f64::consts::E), Some(BigInt::from(-2i32))); assert_eq!(BigInt::from_f64(-0.99999), Some(BigInt::zero())); assert_eq!(BigInt::from_f64(-0.5), Some(BigInt::zero())); assert_eq!(BigInt::from_f64(-0.0), Some(BigInt::zero())); assert_eq!( BigInt::from_f64(f64::MIN_POSITIVE / 2.0), Some(BigInt::zero()) ); assert_eq!(BigInt::from_f64(f64::MIN_POSITIVE), Some(BigInt::zero())); assert_eq!(BigInt::from_f64(0.5), Some(BigInt::zero())); assert_eq!(BigInt::from_f64(0.99999), Some(BigInt::zero())); assert_eq!(BigInt::from_f64(f64::consts::E), Some(BigInt::from(2u32))); assert_eq!(BigInt::from_f64(f64::consts::PI), Some(BigInt::from(3u32))); // special float values assert_eq!(BigInt::from_f64(f64::NAN), None); assert_eq!(BigInt::from_f64(f64::INFINITY), None); assert_eq!(BigInt::from_f64(f64::NEG_INFINITY), None); // largest BigInt that will round to a finite f64 value let big_num = (BigInt::one() << 1024) - BigInt::one() - (BigInt::one() << (1024 - 54)); assert_eq!(big_num.to_f64(), Some(f64::MAX)); assert_eq!((&big_num + BigInt::one()).to_f64(), None); assert_eq!((-&big_num).to_f64(), Some(f64::MIN)); assert_eq!(((-&big_num) - BigInt::one()).to_f64(), None); assert_eq!(((BigInt::one() << 1024) - BigInt::one()).to_f64(), None); assert_eq!((BigInt::one() << 1024).to_f64(), None); assert_eq!((-((BigInt::one() << 1024) - BigInt::one())).to_f64(), None); assert_eq!((-(BigInt::one() << 1024)).to_f64(), None); } #[test] fn test_convert_to_biguint() { fn check(n: BigInt, ans_1: BigUint) { assert_eq!(n.to_biguint().unwrap(), ans_1); assert_eq!(n.to_biguint().unwrap().to_bigint().unwrap(), n); } let zero: BigInt = Zero::zero(); let unsigned_zero: BigUint = Zero::zero(); let positive = BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3])); let negative = -&positive; check(zero, unsigned_zero); check(positive, BigUint::new(vec![1, 2, 3])); assert_eq!(negative.to_biguint(), None); } #[test] fn test_convert_from_uint() { macro_rules! check { ($ty:ident, $max:expr) => { assert_eq!(BigInt::from($ty::zero()), BigInt::zero()); assert_eq!(BigInt::from($ty::one()), BigInt::one()); assert_eq!(BigInt::from($ty::MAX - $ty::one()), $max - BigInt::one()); assert_eq!(BigInt::from($ty::MAX), $max); }; } check!(u8, BigInt::from_slice(Plus, &[u8::MAX as u32])); check!(u16, BigInt::from_slice(Plus, &[u16::MAX as u32])); check!(u32, BigInt::from_slice(Plus, &[u32::MAX])); check!(u64, BigInt::from_slice(Plus, &[u32::MAX, u32::MAX])); #[cfg(has_i128)] check!( u128, BigInt::from_slice(Plus, &[u32::MAX, u32::MAX, u32::MAX, u32::MAX]) ); check!(usize, BigInt::from(usize::MAX as u64)); } #[test] fn test_convert_from_int() { macro_rules! check { ($ty:ident, $min:expr, $max:expr) => { assert_eq!(BigInt::from($ty::MIN), $min); assert_eq!(BigInt::from($ty::MIN + $ty::one()), $min + BigInt::one()); assert_eq!(BigInt::from(-$ty::one()), -BigInt::one()); assert_eq!(BigInt::from($ty::zero()), BigInt::zero()); assert_eq!(BigInt::from($ty::one()), BigInt::one()); assert_eq!(BigInt::from($ty::MAX - $ty::one()), $max - BigInt::one()); assert_eq!(BigInt::from($ty::MAX), $max); }; } check!( i8, BigInt::from_slice(Minus, &[1 << 7]), BigInt::from_slice(Plus, &[i8::MAX as u32]) ); check!( i16, BigInt::from_slice(Minus, &[1 << 15]), BigInt::from_slice(Plus, &[i16::MAX as u32]) ); check!( i32, BigInt::from_slice(Minus, &[1 << 31]), BigInt::from_slice(Plus, &[i32::MAX as u32]) ); check!( i64, BigInt::from_slice(Minus, &[0, 1 << 31]), BigInt::from_slice(Plus, &[u32::MAX, i32::MAX as u32]) ); #[cfg(has_i128)] check!( i128, BigInt::from_slice(Minus, &[0, 0, 0, 1 << 31]), BigInt::from_slice(Plus, &[u32::MAX, u32::MAX, u32::MAX, i32::MAX as u32]) ); check!( isize, BigInt::from(isize::MIN as i64), BigInt::from(isize::MAX as i64) ); } #[test] fn test_convert_from_biguint() { assert_eq!(BigInt::from(BigUint::zero()), BigInt::zero()); assert_eq!(BigInt::from(BigUint::one()), BigInt::one()); assert_eq!( BigInt::from(BigUint::from_slice(&[1, 2, 3])), BigInt::from_slice(Plus, &[1, 2, 3]) ); } #[test] fn test_add() { for elm in SUM_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); let c = BigInt::from_slice(Plus, c_vec); let (na, nb, nc) = (-&a, -&b, -&c); assert_op!(a + b == c); assert_op!(b + a == c); assert_op!(c + na == b); assert_op!(c + nb == a); assert_op!(a + nc == nb); assert_op!(b + nc == na); assert_op!(na + nb == nc); assert_op!(a + na == Zero::zero()); assert_assign_op!(a += b == c); assert_assign_op!(b += a == c); assert_assign_op!(c += na == b); assert_assign_op!(c += nb == a); assert_assign_op!(a += nc == nb); assert_assign_op!(b += nc == na); assert_assign_op!(na += nb == nc); assert_assign_op!(a += na == Zero::zero()); } } #[test] fn test_add_mut() { for elm in SUM_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); let c = BigInt::from_slice(Plus, c_vec); let (na, nb, nc) = (-&a, -&b, -&c); assert_op!(a + b == c); assert_op!(b + a == c); assert_op!(c + na == b); assert_op!(c + nb == a); assert_op!(a + nc == nb); assert_op!(b + nc == na); assert_op!(na + nb == nc); assert_op!(a + na == Zero::zero()); assert_assign_op!(a += b == c); assert_assign_op!(b += a == c); assert_assign_op!(c += na == b); assert_assign_op!(c += nb == a); assert_assign_op!(a += nc == nb); assert_assign_op!(b += nc == na); assert_assign_op!(na += nb == nc); assert_assign_op!(a += na == Zero::zero()); } } #[test] fn test_sub() { for elm in SUM_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); let c = BigInt::from_slice(Plus, c_vec); let (na, nb, nc) = (-&a, -&b, -&c); assert_op!(c - a == b); assert_op!(c - b == a); assert_op!(nb - a == nc); assert_op!(na - b == nc); assert_op!(b - na == c); assert_op!(a - nb == c); assert_op!(nc - na == nb); assert_op!(a - a == Zero::zero()); assert_assign_op!(c -= a == b); assert_assign_op!(c -= b == a); assert_assign_op!(nb -= a == nc); assert_assign_op!(na -= b == nc); assert_assign_op!(b -= na == c); assert_assign_op!(a -= nb == c); assert_assign_op!(nc -= na == nb); assert_assign_op!(a -= a == Zero::zero()); } } #[test] fn test_mul() { for elm in MUL_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); let c = BigInt::from_slice(Plus, c_vec); let (na, nb, nc) = (-&a, -&b, -&c); assert_op!(a * b == c); assert_op!(b * a == c); assert_op!(na * nb == c); assert_op!(na * b == nc); assert_op!(nb * a == nc); assert_assign_op!(a *= b == c); assert_assign_op!(b *= a == c); assert_assign_op!(na *= nb == c); assert_assign_op!(na *= b == nc); assert_assign_op!(nb *= a == nc); } for elm in DIV_REM_QUADRUPLES.iter() { let (a_vec, b_vec, c_vec, d_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); let c = BigInt::from_slice(Plus, c_vec); let d = BigInt::from_slice(Plus, d_vec); assert!(a == &b * &c + &d); assert!(a == &c * &b + &d); } } #[test] fn test_div_mod_floor() { fn check_sub(a: &BigInt, b: &BigInt, ans_d: &BigInt, ans_m: &BigInt) { let (d, m) = a.div_mod_floor(b); if !m.is_zero() { assert_eq!(m.sign(), b.sign()); } assert!(m.abs() <= b.abs()); assert!(*a == b * &d + &m); assert!(d == *ans_d); assert!(m == *ans_m); } fn check(a: &BigInt, b: &BigInt, d: &BigInt, m: &BigInt) { if m.is_zero() { check_sub(a, b, d, m); check_sub(a, &b.neg(), &d.neg(), m); check_sub(&a.neg(), b, &d.neg(), m); check_sub(&a.neg(), &b.neg(), d, m); } else { let one: BigInt = One::one(); check_sub(a, b, d, m); check_sub(a, &b.neg(), &(d.neg() - &one), &(m - b)); check_sub(&a.neg(), b, &(d.neg() - &one), &(b - m)); check_sub(&a.neg(), &b.neg(), d, &m.neg()); } } for elm in MUL_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); let c = BigInt::from_slice(Plus, c_vec); if !a.is_zero() { check(&c, &a, &b, &Zero::zero()); } if !b.is_zero() { check(&c, &b, &a, &Zero::zero()); } } for elm in DIV_REM_QUADRUPLES.iter() { let (a_vec, b_vec, c_vec, d_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); let c = BigInt::from_slice(Plus, c_vec); let d = BigInt::from_slice(Plus, d_vec); if !b.is_zero() { check(&a, &b, &c, &d); } } } #[test] fn test_div_rem() { fn check_sub(a: &BigInt, b: &BigInt, ans_q: &BigInt, ans_r: &BigInt) { let (q, r) = a.div_rem(b); if !r.is_zero() { assert_eq!(r.sign(), a.sign()); } assert!(r.abs() <= b.abs()); assert_eq!(*a, b * &q + &r); assert_eq!(q, *ans_q); assert_eq!(r, *ans_r); let (a, b, ans_q, ans_r) = (a.clone(), b.clone(), ans_q.clone(), ans_r.clone()); assert_op!(a / b == ans_q); assert_op!(a % b == ans_r); assert_assign_op!(a /= b == ans_q); assert_assign_op!(a %= b == ans_r); } fn check(a: &BigInt, b: &BigInt, q: &BigInt, r: &BigInt) { check_sub(a, b, q, r); check_sub(a, &b.neg(), &q.neg(), r); check_sub(&a.neg(), b, &q.neg(), &r.neg()); check_sub(&a.neg(), &b.neg(), q, &r.neg()); } for elm in MUL_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); let c = BigInt::from_slice(Plus, c_vec); if !a.is_zero() { check(&c, &a, &b, &Zero::zero()); } if !b.is_zero() { check(&c, &b, &a, &Zero::zero()); } } for elm in DIV_REM_QUADRUPLES.iter() { let (a_vec, b_vec, c_vec, d_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); let c = BigInt::from_slice(Plus, c_vec); let d = BigInt::from_slice(Plus, d_vec); if !b.is_zero() { check(&a, &b, &c, &d); } } } #[test] fn test_checked_add() { for elm in SUM_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); let c = BigInt::from_slice(Plus, c_vec); assert!(a.checked_add(&b).unwrap() == c); assert!(b.checked_add(&a).unwrap() == c); assert!(c.checked_add(&(-&a)).unwrap() == b); assert!(c.checked_add(&(-&b)).unwrap() == a); assert!(a.checked_add(&(-&c)).unwrap() == (-&b)); assert!(b.checked_add(&(-&c)).unwrap() == (-&a)); assert!((-&a).checked_add(&(-&b)).unwrap() == (-&c)); assert!(a.checked_add(&(-&a)).unwrap() == Zero::zero()); } } #[test] fn test_checked_sub() { for elm in SUM_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); let c = BigInt::from_slice(Plus, c_vec); assert!(c.checked_sub(&a).unwrap() == b); assert!(c.checked_sub(&b).unwrap() == a); assert!((-&b).checked_sub(&a).unwrap() == (-&c)); assert!((-&a).checked_sub(&b).unwrap() == (-&c)); assert!(b.checked_sub(&(-&a)).unwrap() == c); assert!(a.checked_sub(&(-&b)).unwrap() == c); assert!((-&c).checked_sub(&(-&a)).unwrap() == (-&b)); assert!(a.checked_sub(&a).unwrap() == Zero::zero()); } } #[test] fn test_checked_mul() { for elm in MUL_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); let c = BigInt::from_slice(Plus, c_vec); assert!(a.checked_mul(&b).unwrap() == c); assert!(b.checked_mul(&a).unwrap() == c); assert!((-&a).checked_mul(&b).unwrap() == -&c); assert!((-&b).checked_mul(&a).unwrap() == -&c); } for elm in DIV_REM_QUADRUPLES.iter() { let (a_vec, b_vec, c_vec, d_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); let c = BigInt::from_slice(Plus, c_vec); let d = BigInt::from_slice(Plus, d_vec); assert!(a == b.checked_mul(&c).unwrap() + &d); assert!(a == c.checked_mul(&b).unwrap() + &d); } } #[test] fn test_checked_div() { for elm in MUL_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); let c = BigInt::from_slice(Plus, c_vec); if !a.is_zero() { assert!(c.checked_div(&a).unwrap() == b); assert!((-&c).checked_div(&(-&a)).unwrap() == b); assert!((-&c).checked_div(&a).unwrap() == -&b); } if !b.is_zero() { assert!(c.checked_div(&b).unwrap() == a); assert!((-&c).checked_div(&(-&b)).unwrap() == a); assert!((-&c).checked_div(&b).unwrap() == -&a); } assert!(c.checked_div(&Zero::zero()).is_none()); assert!((-&c).checked_div(&Zero::zero()).is_none()); } } #[test] fn test_gcd() { fn check(a: isize, b: isize, c: isize) { let big_a: BigInt = FromPrimitive::from_isize(a).unwrap(); let big_b: BigInt = FromPrimitive::from_isize(b).unwrap(); let big_c: BigInt = FromPrimitive::from_isize(c).unwrap(); assert_eq!(big_a.gcd(&big_b), big_c); } check(10, 2, 2); check(10, 3, 1); check(0, 3, 3); check(3, 3, 3); check(56, 42, 14); check(3, -3, 3); check(-6, 3, 3); check(-4, -2, 2); } #[test] fn test_lcm() { fn check(a: isize, b: isize, c: isize) { let big_a: BigInt = FromPrimitive::from_isize(a).unwrap(); let big_b: BigInt = FromPrimitive::from_isize(b).unwrap(); let big_c: BigInt = FromPrimitive::from_isize(c).unwrap(); assert_eq!(big_a.lcm(&big_b), big_c); } check(1, 0, 0); check(0, 1, 0); check(1, 1, 1); check(-1, 1, 1); check(1, -1, 1); check(-1, -1, 1); check(8, 9, 72); check(11, 5, 55); } #[test] fn test_abs_sub() { let zero: BigInt = Zero::zero(); let one: BigInt = One::one(); assert_eq!((-&one).abs_sub(&one), zero); let one: BigInt = One::one(); let zero: BigInt = Zero::zero(); assert_eq!(one.abs_sub(&one), zero); let one: BigInt = One::one(); let zero: BigInt = Zero::zero(); assert_eq!(one.abs_sub(&zero), one); let one: BigInt = One::one(); let two: BigInt = FromPrimitive::from_isize(2).unwrap(); assert_eq!(one.abs_sub(&-&one), two); } #[test] fn test_from_str_radix() { fn check(s: &str, ans: Option) { let ans = ans.map(|n| { let x: BigInt = FromPrimitive::from_isize(n).unwrap(); x }); assert_eq!(BigInt::from_str_radix(s, 10).ok(), ans); } check("10", Some(10)); check("1", Some(1)); check("0", Some(0)); check("-1", Some(-1)); check("-10", Some(-10)); check("+10", Some(10)); check("--7", None); check("++5", None); check("+-9", None); check("-+3", None); check("Z", None); check("_", None); // issue 10522, this hit an edge case that caused it to // attempt to allocate a vector of size (-1u) == huge. let x: BigInt = format!("1{}", repeat("0").take(36).collect::()) .parse() .unwrap(); let _y = x.to_string(); } #[test] fn test_lower_hex() { let a = BigInt::parse_bytes(b"A", 16).unwrap(); let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap(); assert_eq!(format!("{:x}", a), "a"); assert_eq!(format!("{:x}", hello), "-48656c6c6f20776f726c6421"); assert_eq!(format!("{:♥>+#8x}", a), "♥♥♥♥+0xa"); } #[test] fn test_upper_hex() { let a = BigInt::parse_bytes(b"A", 16).unwrap(); let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap(); assert_eq!(format!("{:X}", a), "A"); assert_eq!(format!("{:X}", hello), "-48656C6C6F20776F726C6421"); assert_eq!(format!("{:♥>+#8X}", a), "♥♥♥♥+0xA"); } #[test] fn test_binary() { let a = BigInt::parse_bytes(b"A", 16).unwrap(); let hello = BigInt::parse_bytes("-224055342307539".as_bytes(), 10).unwrap(); assert_eq!(format!("{:b}", a), "1010"); assert_eq!( format!("{:b}", hello), "-110010111100011011110011000101101001100011010011" ); assert_eq!(format!("{:♥>+#8b}", a), "♥+0b1010"); } #[test] fn test_octal() { let a = BigInt::parse_bytes(b"A", 16).unwrap(); let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap(); assert_eq!(format!("{:o}", a), "12"); assert_eq!(format!("{:o}", hello), "-22062554330674403566756233062041"); assert_eq!(format!("{:♥>+#8o}", a), "♥♥♥+0o12"); } #[test] fn test_display() { let a = BigInt::parse_bytes(b"A", 16).unwrap(); let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap(); assert_eq!(format!("{}", a), "10"); assert_eq!(format!("{}", hello), "-22405534230753963835153736737"); assert_eq!(format!("{:♥>+#8}", a), "♥♥♥♥♥+10"); } #[test] fn test_neg() { assert!(-BigInt::new(Plus, vec![1, 1, 1]) == BigInt::new(Minus, vec![1, 1, 1])); assert!(-BigInt::new(Minus, vec![1, 1, 1]) == BigInt::new(Plus, vec![1, 1, 1])); let zero: BigInt = Zero::zero(); assert_eq!(-&zero, zero); } #[test] fn test_negative_shr() { assert_eq!(BigInt::from(-1) >> 1, BigInt::from(-1)); assert_eq!(BigInt::from(-2) >> 1, BigInt::from(-1)); assert_eq!(BigInt::from(-3) >> 1, BigInt::from(-2)); assert_eq!(BigInt::from(-3) >> 2, BigInt::from(-1)); } #[test] #[cfg(feature = "rand")] fn test_random_shr() { #[cfg(feature = "std")] fn thread_rng() -> impl rand::Rng { rand::thread_rng() } #[cfg(not(feature = "std"))] fn thread_rng() -> impl rand::Rng { use rand::SeedableRng; // Chosen by fair dice roll rand::rngs::StdRng::seed_from_u64(4) } use rand::distributions::Standard; use rand::Rng; let rng = thread_rng(); for p in rng.sample_iter::(&Standard).take(1000) { let big = BigInt::from(p); let bigger = &big << 1000; assert_eq!(&bigger >> 1000, big); for i in 0..64 { let answer = BigInt::from(p >> i); assert_eq!(&big >> i, answer); assert_eq!(&bigger >> (1000 + i), answer); } } } #[test] fn test_iter_sum() { let result: BigInt = FromPrimitive::from_isize(-1234567).unwrap(); let data: Vec = vec![ FromPrimitive::from_i32(-1000000).unwrap(), FromPrimitive::from_i32(-200000).unwrap(), FromPrimitive::from_i32(-30000).unwrap(), FromPrimitive::from_i32(-4000).unwrap(), FromPrimitive::from_i32(-500).unwrap(), FromPrimitive::from_i32(-60).unwrap(), FromPrimitive::from_i32(-7).unwrap(), ]; assert_eq!(result, data.iter().sum()); assert_eq!(result, data.into_iter().sum()); } #[test] fn test_iter_product() { let data: Vec = vec![ FromPrimitive::from_i32(1001).unwrap(), FromPrimitive::from_i32(-1002).unwrap(), FromPrimitive::from_i32(1003).unwrap(), FromPrimitive::from_i32(-1004).unwrap(), FromPrimitive::from_i32(1005).unwrap(), ]; let result = data.get(0).unwrap() * data.get(1).unwrap() * data.get(2).unwrap() * data.get(3).unwrap() * data.get(4).unwrap(); assert_eq!(result, data.iter().product()); assert_eq!(result, data.into_iter().product()); } #[test] fn test_iter_sum_generic() { let result: BigInt = FromPrimitive::from_isize(-1234567).unwrap(); let data = vec![-1000000, -200000, -30000, -4000, -500, -60, -7]; assert_eq!(result, data.iter().sum()); assert_eq!(result, data.into_iter().sum()); } #[test] fn test_iter_product_generic() { let data = vec![1001, -1002, 1003, -1004, 1005]; let result = data[0].to_bigint().unwrap() * data[1].to_bigint().unwrap() * data[2].to_bigint().unwrap() * data[3].to_bigint().unwrap() * data[4].to_bigint().unwrap(); assert_eq!(result, data.iter().product()); assert_eq!(result, data.into_iter().product()); } #[test] fn test_pow() { let one = BigInt::from(1i32); let two = BigInt::from(2i32); let four = BigInt::from(4i32); let eight = BigInt::from(8i32); let minus_two = BigInt::from(-2i32); macro_rules! check { ($t:ty) => { assert_eq!(two.pow(0 as $t), one); assert_eq!(two.pow(1 as $t), two); assert_eq!(two.pow(2 as $t), four); assert_eq!(two.pow(3 as $t), eight); assert_eq!(two.pow(&(3 as $t)), eight); assert_eq!(minus_two.pow(0 as $t), one, "-2^0"); assert_eq!(minus_two.pow(1 as $t), minus_two, "-2^1"); assert_eq!(minus_two.pow(2 as $t), four, "-2^2"); assert_eq!(minus_two.pow(3 as $t), -&eight, "-2^3"); }; } check!(u8); check!(u16); check!(u32); check!(u64); check!(usize); } num-bigint-dig-0.8.2/tests/bigint_bitwise.rs000064400000000000000000000121071046102023000171600ustar 00000000000000extern crate num_bigint_dig as num_bigint; extern crate num_traits; use crate::num_bigint::{BigInt, Sign, ToBigInt}; use num_traits::ToPrimitive; use std::{i32, i64, u32}; enum ValueVec { N, P(&'static [u32]), M(&'static [u32]), } use crate::ValueVec::*; impl ToBigInt for ValueVec { fn to_bigint(&self) -> Option { match self { &N => Some(BigInt::from_slice(Sign::NoSign, &[])), &P(s) => Some(BigInt::from_slice(Sign::Plus, s)), &M(s) => Some(BigInt::from_slice(Sign::Minus, s)), } } } // a, !a const NOT_VALUES: &'static [(ValueVec, ValueVec)] = &[ (N, M(&[1])), (P(&[1]), M(&[2])), (P(&[2]), M(&[3])), (P(&[!0 - 2]), M(&[!0 - 1])), (P(&[!0 - 1]), M(&[!0])), (P(&[!0]), M(&[0, 1])), (P(&[0, 1]), M(&[1, 1])), (P(&[1, 1]), M(&[2, 1])), ]; // a, b, a & b, a | b, a ^ b const BITWISE_VALUES: &'static [(ValueVec, ValueVec, ValueVec, ValueVec, ValueVec)] = &[ (N, N, N, N, N), (N, P(&[1]), N, P(&[1]), P(&[1])), (N, P(&[!0]), N, P(&[!0]), P(&[!0])), (N, P(&[0, 1]), N, P(&[0, 1]), P(&[0, 1])), (N, M(&[1]), N, M(&[1]), M(&[1])), (N, M(&[!0]), N, M(&[!0]), M(&[!0])), (N, M(&[0, 1]), N, M(&[0, 1]), M(&[0, 1])), (P(&[1]), P(&[!0]), P(&[1]), P(&[!0]), P(&[!0 - 1])), (P(&[!0]), P(&[!0]), P(&[!0]), P(&[!0]), N), (P(&[!0]), P(&[1, 1]), P(&[1]), P(&[!0, 1]), P(&[!0 - 1, 1])), (P(&[1]), M(&[!0]), P(&[1]), M(&[!0]), M(&[0, 1])), (P(&[!0]), M(&[1]), P(&[!0]), M(&[1]), M(&[0, 1])), (P(&[!0]), M(&[!0]), P(&[1]), M(&[1]), M(&[2])), (P(&[!0]), M(&[1, 1]), P(&[!0]), M(&[1, 1]), M(&[0, 2])), (P(&[1, 1]), M(&[!0]), P(&[1, 1]), M(&[!0]), M(&[0, 2])), (M(&[1]), M(&[!0]), M(&[!0]), M(&[1]), P(&[!0 - 1])), (M(&[!0]), M(&[!0]), M(&[!0]), M(&[!0]), N), (M(&[!0]), M(&[1, 1]), M(&[!0, 1]), M(&[1]), P(&[!0 - 1, 1])), ]; const I32_MIN: i64 = i32::MIN as i64; const I32_MAX: i64 = i32::MAX as i64; const U32_MAX: i64 = u32::MAX as i64; // some corner cases const I64_VALUES: &'static [i64] = &[ i64::MIN, i64::MIN + 1, i64::MIN + 2, i64::MIN + 3, -U32_MAX - 3, -U32_MAX - 2, -U32_MAX - 1, -U32_MAX, -U32_MAX + 1, -U32_MAX + 2, -U32_MAX + 3, I32_MIN - 3, I32_MIN - 2, I32_MIN - 1, I32_MIN, I32_MIN + 1, I32_MIN + 2, I32_MIN + 3, -3, -2, -1, 0, 1, 2, 3, I32_MAX - 3, I32_MAX - 2, I32_MAX - 1, I32_MAX, I32_MAX + 1, I32_MAX + 2, I32_MAX + 3, U32_MAX - 3, U32_MAX - 2, U32_MAX - 1, U32_MAX, U32_MAX + 1, U32_MAX + 2, U32_MAX + 3, i64::MAX - 3, i64::MAX - 2, i64::MAX - 1, i64::MAX, ]; #[test] fn test_not() { for &(ref a, ref not) in NOT_VALUES.iter() { let a = a.to_bigint().unwrap(); let not = not.to_bigint().unwrap(); // sanity check for tests that fit in i64 if let (Some(prim_a), Some(prim_not)) = (a.to_i64(), not.to_i64()) { assert_eq!(!prim_a, prim_not); } assert_eq!(!a.clone(), not, "!{:x}", a); assert_eq!(!not.clone(), a, "!{:x}", not); } } #[test] fn test_not_i64() { for &prim_a in I64_VALUES.iter() { let a = prim_a.to_bigint().unwrap(); let not = (!prim_a).to_bigint().unwrap(); assert_eq!(!a.clone(), not, "!{:x}", a); } } #[test] fn test_bitwise() { for &(ref a, ref b, ref and, ref or, ref xor) in BITWISE_VALUES.iter() { let a = a.to_bigint().unwrap(); let b = b.to_bigint().unwrap(); let and = and.to_bigint().unwrap(); let or = or.to_bigint().unwrap(); let xor = xor.to_bigint().unwrap(); // sanity check for tests that fit in i64 if let (Some(prim_a), Some(prim_b)) = (a.to_i64(), b.to_i64()) { if let Some(prim_and) = and.to_i64() { assert_eq!(prim_a & prim_b, prim_and); } if let Some(prim_or) = or.to_i64() { assert_eq!(prim_a | prim_b, prim_or); } if let Some(prim_xor) = xor.to_i64() { assert_eq!(prim_a ^ prim_b, prim_xor); } } assert_eq!(a.clone() & &b, and, "{:x} & {:x}", a, b); assert_eq!(b.clone() & &a, and, "{:x} & {:x}", b, a); assert_eq!(a.clone() | &b, or, "{:x} | {:x}", a, b); assert_eq!(b.clone() | &a, or, "{:x} | {:x}", b, a); assert_eq!(a.clone() ^ &b, xor, "{:x} ^ {:x}", a, b); assert_eq!(b.clone() ^ &a, xor, "{:x} ^ {:x}", b, a); } } #[test] fn test_bitwise_i64() { for &prim_a in I64_VALUES.iter() { let a = prim_a.to_bigint().unwrap(); for &prim_b in I64_VALUES.iter() { let b = prim_b.to_bigint().unwrap(); let and = (prim_a & prim_b).to_bigint().unwrap(); let or = (prim_a | prim_b).to_bigint().unwrap(); let xor = (prim_a ^ prim_b).to_bigint().unwrap(); assert_eq!(a.clone() & &b, and, "{:x} & {:x}", a, b); assert_eq!(a.clone() | &b, or, "{:x} | {:x}", a, b); assert_eq!(a.clone() ^ &b, xor, "{:x} ^ {:x}", a, b); } } } num-bigint-dig-0.8.2/tests/bigint_scalar.rs000064400000000000000000000076651046102023000167740ustar 00000000000000extern crate num_bigint_dig as num_bigint; extern crate num_traits; use crate::num_bigint::BigInt; use crate::num_bigint::Sign::Plus; use num_traits::{Signed, ToPrimitive, Zero}; use std::ops::Neg; mod consts; use crate::consts::*; #[macro_use] mod macros; #[test] fn test_scalar_add() { fn check(x: &BigInt, y: &BigInt, z: &BigInt) { let (x, y, z) = (x.clone(), y.clone(), z.clone()); assert_signed_scalar_op!(x + y == z); } for elm in SUM_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); let c = BigInt::from_slice(Plus, c_vec); let (na, nb, nc) = (-&a, -&b, -&c); check(&a, &b, &c); check(&b, &a, &c); check(&c, &na, &b); check(&c, &nb, &a); check(&a, &nc, &nb); check(&b, &nc, &na); check(&na, &nb, &nc); check(&a, &na, &Zero::zero()); } } #[test] fn test_scalar_sub() { fn check(x: &BigInt, y: &BigInt, z: &BigInt) { let (x, y, z) = (x.clone(), y.clone(), z.clone()); assert_signed_scalar_op!(x - y == z); } for elm in SUM_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); let c = BigInt::from_slice(Plus, c_vec); let (na, nb, nc) = (-&a, -&b, -&c); check(&c, &a, &b); check(&c, &b, &a); check(&nb, &a, &nc); check(&na, &b, &nc); check(&b, &na, &c); check(&a, &nb, &c); check(&nc, &na, &nb); check(&a, &a, &Zero::zero()); } } #[test] fn test_scalar_mul() { fn check(x: &BigInt, y: &BigInt, z: &BigInt) { let (x, y, z) = (x.clone(), y.clone(), z.clone()); assert_signed_scalar_op!(x * y == z); } for elm in MUL_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); let c = BigInt::from_slice(Plus, c_vec); let (na, nb, nc) = (-&a, -&b, -&c); check(&a, &b, &c); check(&b, &a, &c); check(&na, &nb, &c); check(&na, &b, &nc); check(&nb, &a, &nc); } } #[test] fn test_scalar_div_rem() { fn check_sub(a: &BigInt, b: u32, ans_q: &BigInt, ans_r: &BigInt) { let (q, r) = (a / b, a % b); if !r.is_zero() { assert_eq!(r.sign(), a.sign()); } assert!(r.abs() <= From::from(b)); assert!(*a == b * &q + &r); assert!(q == *ans_q); assert!(r == *ans_r); let (a, b, ans_q, ans_r) = (a.clone(), b.clone(), ans_q.clone(), ans_r.clone()); assert_op!(a / b == ans_q); assert_op!(a % b == ans_r); if b <= i32::max_value() as u32 { let nb = -(b as i32); assert_op!(a / nb == -ans_q.clone()); assert_op!(a % nb == ans_r); } } fn check(a: &BigInt, b: u32, q: &BigInt, r: &BigInt) { check_sub(a, b, q, r); check_sub(&a.neg(), b, &q.neg(), &r.neg()); } for elm in MUL_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); let c = BigInt::from_slice(Plus, c_vec); if a_vec.len() == 1 && a_vec[0] != 0 { let a = a_vec[0]; check(&c, a, &b, &Zero::zero()); } if b_vec.len() == 1 && b_vec[0] != 0 { let b = b_vec[0]; check(&c, b, &a, &Zero::zero()); } } for elm in DIV_REM_QUADRUPLES.iter() { let (a_vec, b_vec, c_vec, d_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let c = BigInt::from_slice(Plus, c_vec); let d = BigInt::from_slice(Plus, d_vec); if b_vec.len() == 1 && b_vec[0] != 0 { let b = b_vec[0]; check(&a, b, &c, &d); } } } num-bigint-dig-0.8.2/tests/biguint.rs000064400000000000000000001551511046102023000156260ustar 00000000000000extern crate num_bigint_dig as num_bigint; extern crate num_integer; extern crate num_traits; extern crate smallvec; use crate::num_bigint::Sign::Plus; use crate::num_bigint::{BigInt, ToBigInt}; use crate::num_bigint::{BigUint, ToBigUint}; use num_integer::Integer; use std::cmp::Ordering::{Equal, Greater, Less}; use std::collections::hash_map::RandomState; use std::hash::{BuildHasher, Hash, Hasher}; use std::i64; use std::iter::repeat; use std::str::FromStr; use std::{f32, f64}; #[cfg(has_i128)] use std::{i128, u128}; use std::{u16, u32, u64, u8, usize}; use num_traits::{ CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, FromPrimitive, Num, One, Pow, ToPrimitive, Zero, }; use num_traits::float::FloatCore; mod consts; use crate::consts::*; #[macro_use] mod macros; #[test] fn test_from_bytes_be() { fn check(s: &str, result: &str) { assert_eq!( BigUint::from_bytes_be(s.as_bytes()), BigUint::parse_bytes(result.as_bytes(), 10).unwrap() ); } check("A", "65"); check("AA", "16705"); check("AB", "16706"); check("Hello world!", "22405534230753963835153736737"); assert_eq!(BigUint::from_bytes_be(&[]), Zero::zero()); } #[test] fn test_to_bytes_be() { fn check(s: &str, result: &str) { let b = BigUint::parse_bytes(result.as_bytes(), 10).unwrap(); assert_eq!(b.to_bytes_be(), s.as_bytes()); } check("A", "65"); check("AA", "16705"); check("AB", "16706"); check("Hello world!", "22405534230753963835153736737"); let b: BigUint = Zero::zero(); assert_eq!(b.to_bytes_be(), [0]); // Test with leading/trailing zero bytes and a full BigDigit of value 0 let b = BigUint::from_str_radix("00010000000000000200", 16).unwrap(); assert_eq!(b.to_bytes_be(), [1, 0, 0, 0, 0, 0, 0, 2, 0]); } #[test] fn test_from_bytes_le() { fn check(s: &str, result: &str) { assert_eq!( BigUint::from_bytes_le(s.as_bytes()), BigUint::parse_bytes(result.as_bytes(), 10).unwrap() ); } check("A", "65"); check("AA", "16705"); check("BA", "16706"); check("!dlrow olleH", "22405534230753963835153736737"); assert_eq!(BigUint::from_bytes_le(&[]), Zero::zero()); } #[test] fn test_to_bytes_le() { fn check(s: &str, result: &str) { let b = BigUint::parse_bytes(result.as_bytes(), 10).unwrap(); assert_eq!(b.to_bytes_le(), s.as_bytes()); } check("A", "65"); check("AA", "16705"); check("BA", "16706"); check("!dlrow olleH", "22405534230753963835153736737"); let b: BigUint = Zero::zero(); assert_eq!(b.to_bytes_le(), [0]); // Test with leading/trailing zero bytes and a full BigDigit of value 0 let b = BigUint::from_str_radix("00010000000000000200", 16).unwrap(); assert_eq!(b.to_bytes_le(), [0, 2, 0, 0, 0, 0, 0, 0, 1]); } #[test] fn test_cmp() { let data: [&[_]; 7] = [&[], &[1], &[2], &[!0], &[0, 1], &[2, 1], &[1, 1, 1]]; let data: Vec = data.iter().map(|v| BigUint::from_slice(*v)).collect(); for (i, ni) in data.iter().enumerate() { for (j0, nj) in data[i..].iter().enumerate() { let j = j0 + i; if i == j { assert_eq!(ni.cmp(nj), Equal); assert_eq!(nj.cmp(ni), Equal); assert_eq!(ni, nj); assert!(!(ni != nj)); assert!(ni <= nj); assert!(ni >= nj); assert!(!(ni < nj)); assert!(!(ni > nj)); } else { assert_eq!(ni.cmp(nj), Less); assert_eq!(nj.cmp(ni), Greater); assert!(!(ni == nj)); assert!(ni != nj); assert!(ni <= nj); assert!(!(ni >= nj)); assert!(ni < nj); assert!(!(ni > nj)); assert!(!(nj <= ni)); assert!(nj >= ni); assert!(!(nj < ni)); assert!(nj > ni); } } } } fn hash(x: &T) -> u64 { let mut hasher = ::Hasher::new(); x.hash(&mut hasher); hasher.finish() } #[test] fn test_hash() { use crate::hash; let a = BigUint::new(vec![]); let b = BigUint::new(vec![0]); let c = BigUint::new(vec![1]); let d = BigUint::new(vec![1, 0, 0, 0, 0, 0]); let e = BigUint::new(vec![0, 0, 0, 0, 0, 1]); assert!(hash(&a) == hash(&b)); assert!(hash(&b) != hash(&c)); assert!(hash(&c) == hash(&d)); assert!(hash(&d) != hash(&e)); } // LEFT, RIGHT, AND, OR, XOR const BIT_TESTS: &'static [( &'static [u32], &'static [u32], &'static [u32], &'static [u32], &'static [u32], )] = &[ (&[], &[], &[], &[], &[]), (&[1, 0, 1], &[1, 1], &[1], &[1, 1, 1], &[0, 1, 1]), (&[1, 0, 1], &[0, 1, 1], &[0, 0, 1], &[1, 1, 1], &[1, 1]), ( &[268, 482, 17], &[964, 54], &[260, 34], &[972, 502, 17], &[712, 468, 17], ), ]; #[test] fn test_bitand() { for elm in BIT_TESTS { let (a_vec, b_vec, c_vec, _, _) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); let c = BigUint::from_slice(c_vec); assert_op!(a & b == c); assert_op!(b & a == c); assert_assign_op!(a &= b == c); assert_assign_op!(b &= a == c); } } #[test] fn test_bitor() { for elm in BIT_TESTS { let (a_vec, b_vec, _, c_vec, _) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); let c = BigUint::from_slice(c_vec); assert_op!(a | b == c); assert_op!(b | a == c); assert_assign_op!(a |= b == c); assert_assign_op!(b |= a == c); } } #[test] fn test_bitxor() { for elm in BIT_TESTS { let (a_vec, b_vec, _, _, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); let c = BigUint::from_slice(c_vec); assert_op!(a ^ b == c); assert_op!(b ^ a == c); assert_op!(a ^ c == b); assert_op!(c ^ a == b); assert_op!(b ^ c == a); assert_op!(c ^ b == a); assert_assign_op!(a ^= b == c); assert_assign_op!(b ^= a == c); assert_assign_op!(a ^= c == b); assert_assign_op!(c ^= a == b); assert_assign_op!(b ^= c == a); assert_assign_op!(c ^= b == a); } } #[test] fn test_shl() { fn check(s: &str, shift: usize, ans: &str) { let opt_biguint = BigUint::from_str_radix(s, 16).ok(); let mut bu_assign = opt_biguint.unwrap(); let bu = (bu_assign.clone() << shift).to_str_radix(16); assert_eq!(bu, ans); bu_assign <<= shift; assert_eq!(bu_assign.to_str_radix(16), ans); } check("0", 3, "0"); check("1", 3, "8"); check( "1\ 0000\ 0000\ 0000\ 0001\ 0000\ 0000\ 0000\ 0001", 3, "8\ 0000\ 0000\ 0000\ 0008\ 0000\ 0000\ 0000\ 0008", ); check( "1\ 0000\ 0001\ 0000\ 0001", 2, "4\ 0000\ 0004\ 0000\ 0004", ); check( "1\ 0001\ 0001", 1, "2\ 0002\ 0002", ); check( "\ 4000\ 0000\ 0000\ 0000", 3, "2\ 0000\ 0000\ 0000\ 0000", ); check( "4000\ 0000", 2, "1\ 0000\ 0000", ); check( "4000", 2, "1\ 0000", ); check( "4000\ 0000\ 0000\ 0000", 67, "2\ 0000\ 0000\ 0000\ 0000\ 0000\ 0000\ 0000\ 0000", ); check( "4000\ 0000", 35, "2\ 0000\ 0000\ 0000\ 0000", ); check( "4000", 19, "2\ 0000\ 0000", ); check( "fedc\ ba98\ 7654\ 3210\ fedc\ ba98\ 7654\ 3210", 4, "f\ edcb\ a987\ 6543\ 210f\ edcb\ a987\ 6543\ 2100", ); check( "88887777666655554444333322221111", 16, "888877776666555544443333222211110000", ); } #[test] fn test_shr() { fn check(s: &str, shift: usize, ans: &str) { let opt_biguint = BigUint::from_str_radix(s, 16).ok(); let mut bu_assign = opt_biguint.unwrap(); let bu = (bu_assign.clone() >> shift).to_str_radix(16); assert_eq!(bu, ans); bu_assign >>= shift; assert_eq!(bu_assign.to_str_radix(16), ans); } check("0", 3, "0"); check("f", 3, "1"); check( "1\ 0000\ 0000\ 0000\ 0001\ 0000\ 0000\ 0000\ 0001", 3, "2000\ 0000\ 0000\ 0000\ 2000\ 0000\ 0000\ 0000", ); check( "1\ 0000\ 0001\ 0000\ 0001", 2, "4000\ 0000\ 4000\ 0000", ); check( "1\ 0001\ 0001", 1, "8000\ 8000", ); check( "2\ 0000\ 0000\ 0000\ 0001\ 0000\ 0000\ 0000\ 0001", 67, "4000\ 0000\ 0000\ 0000", ); check( "2\ 0000\ 0001\ 0000\ 0001", 35, "4000\ 0000", ); check( "2\ 0001\ 0001", 19, "4000", ); check( "1\ 0000\ 0000\ 0000\ 0000", 1, "8000\ 0000\ 0000\ 0000", ); check( "1\ 0000\ 0000", 1, "8000\ 0000", ); check( "1\ 0000", 1, "8000", ); check( "f\ edcb\ a987\ 6543\ 210f\ edcb\ a987\ 6543\ 2100", 4, "fedc\ ba98\ 7654\ 3210\ fedc\ ba98\ 7654\ 3210", ); check( "888877776666555544443333222211110000", 16, "88887777666655554444333322221111", ); } // `DoubleBigDigit` size dependent #[test] fn test_convert_i64() { fn check(b1: BigUint, i: i64) { let b2: BigUint = FromPrimitive::from_i64(i).unwrap(); assert_eq!(b1, b2); assert_eq!(b1.to_i64().unwrap(), i); } check(Zero::zero(), 0); check(One::one(), 1); check(i64::MAX.to_biguint().unwrap(), i64::MAX); check(BigUint::new(vec![]), 0); check(BigUint::new(vec![1]), 1); check(BigUint::new(vec![N1]), (1 << 32) - 1); check(BigUint::new(vec![0, 1]), 1 << 32); check(BigUint::new(vec![N1, N1 >> 1]), i64::MAX); assert_eq!(i64::MIN.to_biguint(), None); assert_eq!(BigUint::new(vec![N1, N1]).to_i64(), None); assert_eq!(BigUint::new(vec![0, 0, 1]).to_i64(), None); assert_eq!(BigUint::new(vec![N1, N1, N1]).to_i64(), None); } #[test] #[cfg(has_i128)] fn test_convert_i128() { fn check(b1: BigUint, i: i128) { let b2: BigUint = FromPrimitive::from_i128(i).unwrap(); assert_eq!(b1, b2); assert_eq!(b1.to_i128().unwrap(), i); } check(Zero::zero(), 0); check(One::one(), 1); check(i128::MAX.to_biguint().unwrap(), i128::MAX); check(BigUint::new(vec![]), 0); check(BigUint::new(vec![1]), 1); check(BigUint::new(vec![N1]), (1 << 32) - 1); check(BigUint::new(vec![0, 1]), 1 << 32); check(BigUint::new(vec![N1, N1, N1, N1 >> 1]), i128::MAX); assert_eq!(i128::MIN.to_biguint(), None); assert_eq!(BigUint::new(vec![N1, N1, N1, N1]).to_i128(), None); assert_eq!(BigUint::new(vec![0, 0, 0, 0, 1]).to_i128(), None); assert_eq!(BigUint::new(vec![N1, N1, N1, N1, N1]).to_i128(), None); } // `DoubleBigDigit` size dependent #[test] fn test_convert_u64() { fn check(b1: BigUint, u: u64) { let b2: BigUint = FromPrimitive::from_u64(u).unwrap(); assert_eq!(b1, b2); assert_eq!(b1.to_u64().unwrap(), u); } check(Zero::zero(), 0); check(One::one(), 1); check(u64::MIN.to_biguint().unwrap(), u64::MIN); check(u64::MAX.to_biguint().unwrap(), u64::MAX); check(BigUint::new(vec![]), 0); check(BigUint::new(vec![1]), 1); check(BigUint::new(vec![N1]), (1 << 32) - 1); check(BigUint::new(vec![0, 1]), 1 << 32); check(BigUint::new(vec![N1, N1]), u64::MAX); assert_eq!(BigUint::new(vec![0, 0, 1]).to_u64(), None); assert_eq!(BigUint::new(vec![N1, N1, N1]).to_u64(), None); } #[test] #[cfg(has_i128)] fn test_convert_u128() { fn check(b1: BigUint, u: u128) { let b2: BigUint = FromPrimitive::from_u128(u).unwrap(); assert_eq!(b1, b2); assert_eq!(b1.to_u128().unwrap(), u); } check(Zero::zero(), 0); check(One::one(), 1); check(u128::MIN.to_biguint().unwrap(), u128::MIN); check(u128::MAX.to_biguint().unwrap(), u128::MAX); check(BigUint::new(vec![]), 0); check(BigUint::new(vec![1]), 1); check(BigUint::new(vec![N1]), (1 << 32) - 1); check(BigUint::new(vec![0, 1]), 1 << 32); check(BigUint::new(vec![N1, N1, N1, N1]), u128::MAX); assert_eq!(BigUint::new(vec![0, 0, 0, 0, 1]).to_u128(), None); assert_eq!(BigUint::new(vec![N1, N1, N1, N1, N1]).to_u128(), None); } #[test] fn test_convert_f32() { fn check(b1: &BigUint, f: f32) { let b2 = BigUint::from_f32(f).unwrap(); assert_eq!(b1, &b2); assert_eq!(b1.to_f32().unwrap(), f); } check(&BigUint::zero(), 0.0); check(&BigUint::one(), 1.0); check(&BigUint::from(u16::MAX), 2.0.powi(16) - 1.0); check(&BigUint::from(1u64 << 32), 2.0.powi(32)); check(&BigUint::from_slice(&[0, 0, 1]), 2.0.powi(64)); check( &((BigUint::one() << 100) + (BigUint::one() << 123)), 2.0.powi(100) + 2.0.powi(123), ); check(&(BigUint::one() << 127), 2.0.powi(127)); check(&(BigUint::from((1u64 << 24) - 1) << (128 - 24)), f32::MAX); // keeping all 24 digits with the bits at different offsets to the BigDigits let x: u32 = 0b00000000101111011111011011011101; let mut f = x as f32; let mut b = BigUint::from(x); for _ in 0..64 { check(&b, f); f *= 2.0; b = b << 1; } // this number when rounded to f64 then f32 isn't the same as when rounded straight to f32 let n: u64 = 0b0000000000111111111111111111111111011111111111111111111111111111; assert!((n as f64) as f32 != n as f32); assert_eq!(BigUint::from(n).to_f32(), Some(n as f32)); // test rounding up with the bits at different offsets to the BigDigits let mut f = ((1u64 << 25) - 1) as f32; let mut b = BigUint::from(1u64 << 25); for _ in 0..64 { assert_eq!(b.to_f32(), Some(f)); f *= 2.0; b = b << 1; } // rounding assert_eq!(BigUint::from_f32(-1.0), None); assert_eq!(BigUint::from_f32(-0.99999), Some(BigUint::zero())); assert_eq!(BigUint::from_f32(-0.5), Some(BigUint::zero())); assert_eq!(BigUint::from_f32(-0.0), Some(BigUint::zero())); assert_eq!( BigUint::from_f32(f32::MIN_POSITIVE / 2.0), Some(BigUint::zero()) ); assert_eq!(BigUint::from_f32(f32::MIN_POSITIVE), Some(BigUint::zero())); assert_eq!(BigUint::from_f32(0.5), Some(BigUint::zero())); assert_eq!(BigUint::from_f32(0.99999), Some(BigUint::zero())); assert_eq!(BigUint::from_f32(f32::consts::E), Some(BigUint::from(2u32))); assert_eq!( BigUint::from_f32(f32::consts::PI), Some(BigUint::from(3u32)) ); // special float values assert_eq!(BigUint::from_f32(f32::NAN), None); assert_eq!(BigUint::from_f32(f32::INFINITY), None); assert_eq!(BigUint::from_f32(f32::NEG_INFINITY), None); assert_eq!(BigUint::from_f32(f32::MIN), None); // largest BigUint that will round to a finite f32 value let big_num = (BigUint::one() << 128) - BigUint::one() - (BigUint::one() << (128 - 25)); assert_eq!(big_num.to_f32(), Some(f32::MAX)); assert_eq!((big_num + BigUint::one()).to_f32(), None); assert_eq!(((BigUint::one() << 128) - BigUint::one()).to_f32(), None); assert_eq!((BigUint::one() << 128).to_f32(), None); } #[test] fn test_convert_f64() { fn check(b1: &BigUint, f: f64) { let b2 = BigUint::from_f64(f).unwrap(); assert_eq!(b1, &b2); assert_eq!(b1.to_f64().unwrap(), f); } check(&BigUint::zero(), 0.0); check(&BigUint::one(), 1.0); check(&BigUint::from(u32::MAX), 2.0.powi(32) - 1.0); check(&BigUint::from(1u64 << 32), 2.0.powi(32)); check(&BigUint::from_slice(&[0, 0, 1]), 2.0.powi(64)); check( &((BigUint::one() << 100) + (BigUint::one() << 152)), 2.0.powi(100) + 2.0.powi(152), ); check(&(BigUint::one() << 1023), 2.0.powi(1023)); check(&(BigUint::from((1u64 << 53) - 1) << (1024 - 53)), f64::MAX); // keeping all 53 digits with the bits at different offsets to the BigDigits let x: u64 = 0b0000000000011110111110110111111101110111101111011111011011011101; let mut f = x as f64; let mut b = BigUint::from(x); for _ in 0..128 { check(&b, f); f *= 2.0; b = b << 1; } // test rounding up with the bits at different offsets to the BigDigits let mut f = ((1u64 << 54) - 1) as f64; let mut b = BigUint::from(1u64 << 54); for _ in 0..128 { assert_eq!(b.to_f64(), Some(f)); f *= 2.0; b = b << 1; } // rounding assert_eq!(BigUint::from_f64(-1.0), None); assert_eq!(BigUint::from_f64(-0.99999), Some(BigUint::zero())); assert_eq!(BigUint::from_f64(-0.5), Some(BigUint::zero())); assert_eq!(BigUint::from_f64(-0.0), Some(BigUint::zero())); assert_eq!( BigUint::from_f64(f64::MIN_POSITIVE / 2.0), Some(BigUint::zero()) ); assert_eq!(BigUint::from_f64(f64::MIN_POSITIVE), Some(BigUint::zero())); assert_eq!(BigUint::from_f64(0.5), Some(BigUint::zero())); assert_eq!(BigUint::from_f64(0.99999), Some(BigUint::zero())); assert_eq!(BigUint::from_f64(f64::consts::E), Some(BigUint::from(2u32))); assert_eq!( BigUint::from_f64(f64::consts::PI), Some(BigUint::from(3u32)) ); // special float values assert_eq!(BigUint::from_f64(f64::NAN), None); assert_eq!(BigUint::from_f64(f64::INFINITY), None); assert_eq!(BigUint::from_f64(f64::NEG_INFINITY), None); assert_eq!(BigUint::from_f64(f64::MIN), None); // largest BigUint that will round to a finite f64 value let big_num = (BigUint::one() << 1024) - BigUint::one() - (BigUint::one() << (1024 - 54)); assert_eq!(big_num.to_f64(), Some(f64::MAX)); assert_eq!((big_num + BigUint::one()).to_f64(), None); assert_eq!(((BigInt::one() << 1024) - BigInt::one()).to_f64(), None); assert_eq!((BigUint::one() << 1024).to_f64(), None); } #[test] fn test_convert_to_bigint() { fn check(n: BigUint, ans: BigInt) { assert_eq!(n.to_bigint().unwrap(), ans); assert_eq!(n.to_bigint().unwrap().to_biguint().unwrap(), n); } check(Zero::zero(), Zero::zero()); check( BigUint::new(vec![1, 2, 3]), BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3])), ); } #[test] fn test_convert_from_uint() { macro_rules! check { ($ty:ident, $max:expr) => { assert_eq!(BigUint::from($ty::zero()), BigUint::zero()); assert_eq!(BigUint::from($ty::one()), BigUint::one()); assert_eq!(BigUint::from($ty::MAX - $ty::one()), $max - BigUint::one()); assert_eq!(BigUint::from($ty::MAX), $max); }; } check!(u8, BigUint::from_slice(&[u8::MAX as u32])); check!(u16, BigUint::from_slice(&[u16::MAX as u32])); check!(u32, BigUint::from_slice(&[u32::MAX])); check!(u64, BigUint::from_slice(&[u32::MAX, u32::MAX])); #[cfg(has_i128)] check!( u128, BigUint::from_slice(&[u32::MAX, u32::MAX, u32::MAX, u32::MAX]) ); check!(usize, BigUint::from(usize::MAX as u64)); } #[test] fn test_add() { for elm in SUM_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); let c = BigUint::from_slice(c_vec); assert_op!(a + b == c); assert_op!(b + a == c); assert_assign_op!(a += b == c); assert_assign_op!(b += a == c); } } #[test] fn test_sub() { for elm in SUM_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); let c = BigUint::from_slice(c_vec); assert_op!(c - a == b); assert_op!(c - b == a); assert_assign_op!(c -= a == b); assert_assign_op!(c -= b == a); } } #[test] #[should_panic] fn test_sub_fail_on_underflow() { let (a, b): (BigUint, BigUint) = (Zero::zero(), One::one()); let _ = a - b; } #[test] fn test_mul() { for elm in MUL_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); let c = BigUint::from_slice(c_vec); assert_op!(a * b == c); assert_op!(b * a == c); assert_assign_op!(a *= b == c); assert_assign_op!(b *= a == c); } for elm in DIV_REM_QUADRUPLES.iter() { let (a_vec, b_vec, c_vec, d_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); let c = BigUint::from_slice(c_vec); let d = BigUint::from_slice(d_vec); assert!(a == &b * &c + &d); assert!(a == &c * &b + &d); } } #[test] fn test_div_rem() { for elm in MUL_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); let c = BigUint::from_slice(c_vec); if !a.is_zero() { assert_op!(c / a == b); assert_op!(c % a == Zero::zero()); assert_assign_op!(c /= a == b); assert_assign_op!(c %= a == Zero::zero()); assert_eq!(c.div_rem(&a), (b.clone(), Zero::zero())); } if !b.is_zero() { assert_op!(c / b == a); assert_op!(c % b == Zero::zero()); assert_assign_op!(c /= b == a); assert_assign_op!(c %= b == Zero::zero()); assert_eq!(c.div_rem(&b), (a.clone(), Zero::zero())); } } for elm in DIV_REM_QUADRUPLES.iter() { let (a_vec, b_vec, c_vec, d_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); let c = BigUint::from_slice(c_vec); let d = BigUint::from_slice(d_vec); if !b.is_zero() { assert_op!(a / b == c); assert_op!(a % b == d); assert_assign_op!(a /= b == c); assert_assign_op!(a %= b == d); assert!(a.div_rem(&b) == (c, d)); } } } #[test] fn test_checked_add() { for elm in SUM_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); let c = BigUint::from_slice(c_vec); assert!(a.checked_add(&b).unwrap() == c); assert!(b.checked_add(&a).unwrap() == c); } } #[test] fn test_checked_sub() { for elm in SUM_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); let c = BigUint::from_slice(c_vec); assert!(c.checked_sub(&a).unwrap() == b); assert!(c.checked_sub(&b).unwrap() == a); if a > c { assert!(a.checked_sub(&c).is_none()); } if b > c { assert!(b.checked_sub(&c).is_none()); } } } #[test] fn test_checked_mul() { for elm in MUL_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); let c = BigUint::from_slice(c_vec); assert!(a.checked_mul(&b).unwrap() == c); assert!(b.checked_mul(&a).unwrap() == c); } for elm in DIV_REM_QUADRUPLES.iter() { let (a_vec, b_vec, c_vec, d_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); let c = BigUint::from_slice(c_vec); let d = BigUint::from_slice(d_vec); assert!(a == b.checked_mul(&c).unwrap() + &d); assert!(a == c.checked_mul(&b).unwrap() + &d); } } #[test] fn test_mul_overflow() { /* Test for issue #187 - overflow due to mac3 incorrectly sizing temporary */ let s = "531137992816767098689588206552468627329593117727031923199444138200403559860852242739162502232636710047537552105951370000796528760829212940754539968588340162273730474622005920097370111"; let a: BigUint = s.parse().unwrap(); let b = a.clone(); let _ = a.checked_mul(&b); } #[test] fn test_checked_div() { for elm in MUL_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); let c = BigUint::from_slice(c_vec); if !a.is_zero() { assert!(c.checked_div(&a).unwrap() == b); } if !b.is_zero() { assert!(c.checked_div(&b).unwrap() == a); } assert!(c.checked_div(&Zero::zero()).is_none()); } } #[test] fn test_gcd() { fn check(a: usize, b: usize, c: usize) { let big_a: BigUint = FromPrimitive::from_usize(a).unwrap(); let big_b: BigUint = FromPrimitive::from_usize(b).unwrap(); let big_c: BigUint = FromPrimitive::from_usize(c).unwrap(); assert_eq!(big_a.gcd(&big_b), big_c); } check(10, 2, 2); check(10, 3, 1); check(0, 3, 3); check(3, 3, 3); check(56, 42, 14); } #[test] fn test_lcm() { fn check(a: usize, b: usize, c: usize) { let big_a: BigUint = FromPrimitive::from_usize(a).unwrap(); let big_b: BigUint = FromPrimitive::from_usize(b).unwrap(); let big_c: BigUint = FromPrimitive::from_usize(c).unwrap(); assert_eq!(big_a.lcm(&big_b), big_c); } check(1, 0, 0); check(0, 1, 0); check(1, 1, 1); check(8, 9, 72); check(11, 5, 55); check(99, 17, 1683); } #[test] fn test_is_even() { let one: BigUint = FromStr::from_str("1").unwrap(); let two: BigUint = FromStr::from_str("2").unwrap(); let thousand: BigUint = FromStr::from_str("1000").unwrap(); let big: BigUint = FromStr::from_str("1000000000000000000000").unwrap(); let bigger: BigUint = FromStr::from_str("1000000000000000000001").unwrap(); assert!(one.is_odd()); assert!(two.is_even()); assert!(thousand.is_even()); assert!(big.is_even()); assert!(bigger.is_odd()); assert!((&one << 64).is_even()); assert!(((&one << 64) + one).is_odd()); } fn to_str_pairs() -> Vec<(BigUint, Vec<(u32, String)>)> { let bits = 32; vec![ ( Zero::zero(), vec![(2, "0".to_string()), (3, "0".to_string())], ), ( BigUint::from_slice(&[0xff]), vec![ (2, "11111111".to_string()), (3, "100110".to_string()), (4, "3333".to_string()), (5, "2010".to_string()), (6, "1103".to_string()), (7, "513".to_string()), (8, "377".to_string()), (9, "313".to_string()), (10, "255".to_string()), (11, "212".to_string()), (12, "193".to_string()), (13, "168".to_string()), (14, "143".to_string()), (15, "120".to_string()), (16, "ff".to_string()), ], ), ( BigUint::from_slice(&[0xfff]), vec![ (2, "111111111111".to_string()), (4, "333333".to_string()), (16, "fff".to_string()), ], ), ( BigUint::from_slice(&[1, 2]), vec![ ( 2, format!("10{}1", repeat("0").take(bits - 1).collect::()), ), ( 4, format!("2{}1", repeat("0").take(bits / 2 - 1).collect::()), ), ( 10, match bits { 64 => "36893488147419103233".to_string(), 32 => "8589934593".to_string(), 16 => "131073".to_string(), _ => panic!(), }, ), ( 16, format!("2{}1", repeat("0").take(bits / 4 - 1).collect::()), ), ], ), ( BigUint::from_slice(&[1, 2, 3]), vec![ ( 2, format!( "11{}10{}1", repeat("0").take(bits - 2).collect::(), repeat("0").take(bits - 1).collect::() ), ), ( 4, format!( "3{}2{}1", repeat("0").take(bits / 2 - 1).collect::(), repeat("0").take(bits / 2 - 1).collect::() ), ), ( 8, match bits { 64 => "14000000000000000000004000000000000000000001".to_string(), 32 => "6000000000100000000001".to_string(), 16 => "140000400001".to_string(), _ => panic!(), }, ), ( 10, match bits { 64 => "1020847100762815390427017310442723737601".to_string(), 32 => "55340232229718589441".to_string(), 16 => "12885032961".to_string(), _ => panic!(), }, ), ( 16, format!( "3{}2{}1", repeat("0").take(bits / 4 - 1).collect::(), repeat("0").take(bits / 4 - 1).collect::() ), ), ], ), ] } #[test] fn test_to_str_radix() { let r = to_str_pairs(); for num_pair in r.iter() { let &(ref n, ref rs) = num_pair; for str_pair in rs.iter() { let &(ref radix, ref str) = str_pair; assert_eq!(n.to_str_radix(*radix), *str); } } } #[test] fn test_from_and_to_radix() { const GROUND_TRUTH: &'static [(&'static [u8], u32, &'static [u8])] = &[ (b"0", 42, &[0]), ( b"ffffeeffbb", 2, &[ 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ], ), ( b"ffffeeffbb", 3, &[ 2, 2, 1, 1, 2, 1, 1, 2, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 1, 0, 0, 2, 2, 0, 1, ], ), ( b"ffffeeffbb", 4, &[3, 2, 3, 2, 3, 3, 3, 3, 2, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3], ), ( b"ffffeeffbb", 5, &[0, 4, 3, 3, 1, 4, 2, 4, 1, 4, 4, 2, 3, 0, 0, 1, 2, 1], ), ( b"ffffeeffbb", 6, &[5, 5, 4, 5, 5, 0, 0, 1, 2, 5, 3, 0, 1, 0, 2, 2], ), ( b"ffffeeffbb", 7, &[4, 2, 3, 6, 0, 1, 6, 1, 6, 2, 0, 3, 2, 4, 1], ), ( b"ffffeeffbb", 8, &[3, 7, 6, 7, 7, 5, 3, 7, 7, 7, 7, 7, 7, 1], ), (b"ffffeeffbb", 9, &[8, 4, 5, 7, 0, 0, 3, 2, 0, 3, 0, 8, 3]), (b"ffffeeffbb", 10, &[5, 9, 5, 3, 1, 5, 0, 1, 5, 9, 9, 0, 1]), (b"ffffeeffbb", 11, &[10, 7, 6, 5, 2, 0, 3, 3, 3, 4, 9, 3]), (b"ffffeeffbb", 12, &[11, 8, 5, 10, 1, 10, 3, 1, 1, 9, 5, 1]), (b"ffffeeffbb", 13, &[0, 5, 7, 4, 6, 5, 6, 11, 8, 12, 7]), (b"ffffeeffbb", 14, &[11, 4, 4, 11, 8, 4, 6, 0, 3, 11, 3]), (b"ffffeeffbb", 15, &[5, 11, 13, 2, 1, 10, 2, 0, 9, 13, 1]), (b"ffffeeffbb", 16, &[11, 11, 15, 15, 14, 14, 15, 15, 15, 15]), (b"ffffeeffbb", 17, &[0, 2, 14, 12, 2, 14, 8, 10, 4, 9]), (b"ffffeeffbb", 18, &[17, 15, 5, 13, 10, 16, 16, 13, 9, 5]), (b"ffffeeffbb", 19, &[14, 13, 2, 8, 9, 0, 1, 14, 7, 3]), (b"ffffeeffbb", 20, &[15, 19, 3, 14, 0, 17, 19, 18, 2, 2]), (b"ffffeeffbb", 21, &[11, 5, 4, 13, 5, 18, 9, 1, 8, 1]), (b"ffffeeffbb", 22, &[21, 3, 7, 21, 15, 12, 17, 0, 20]), (b"ffffeeffbb", 23, &[21, 21, 6, 9, 10, 7, 21, 0, 14]), (b"ffffeeffbb", 24, &[11, 10, 19, 14, 22, 11, 17, 23, 9]), (b"ffffeeffbb", 25, &[20, 18, 21, 22, 21, 14, 3, 5, 7]), (b"ffffeeffbb", 26, &[13, 15, 24, 11, 17, 6, 23, 6, 5]), (b"ffffeeffbb", 27, &[17, 16, 7, 0, 21, 0, 3, 24, 3]), (b"ffffeeffbb", 28, &[11, 16, 11, 15, 14, 18, 13, 25, 2]), (b"ffffeeffbb", 29, &[6, 8, 7, 19, 14, 13, 21, 5, 2]), (b"ffffeeffbb", 30, &[5, 13, 18, 11, 10, 7, 8, 20, 1]), (b"ffffeeffbb", 31, &[22, 26, 15, 19, 8, 27, 29, 8, 1]), (b"ffffeeffbb", 32, &[27, 29, 31, 29, 30, 31, 31, 31]), (b"ffffeeffbb", 33, &[32, 20, 27, 12, 1, 12, 26, 25]), (b"ffffeeffbb", 34, &[17, 9, 16, 33, 13, 25, 31, 20]), (b"ffffeeffbb", 35, &[25, 32, 2, 25, 11, 4, 3, 17]), (b"ffffeeffbb", 36, &[35, 34, 5, 6, 32, 3, 1, 14]), (b"ffffeeffbb", 37, &[16, 21, 18, 4, 33, 19, 21, 11]), (b"ffffeeffbb", 38, &[33, 25, 19, 29, 20, 6, 23, 9]), (b"ffffeeffbb", 39, &[26, 27, 29, 23, 16, 18, 0, 8]), (b"ffffeeffbb", 40, &[35, 39, 30, 11, 16, 17, 28, 6]), (b"ffffeeffbb", 41, &[36, 30, 9, 18, 12, 19, 26, 5]), (b"ffffeeffbb", 42, &[11, 34, 37, 27, 1, 13, 32, 4]), (b"ffffeeffbb", 43, &[3, 24, 11, 2, 10, 40, 1, 4]), (b"ffffeeffbb", 44, &[43, 12, 40, 32, 3, 23, 19, 3]), (b"ffffeeffbb", 45, &[35, 38, 44, 18, 22, 18, 42, 2]), (b"ffffeeffbb", 46, &[21, 45, 18, 41, 17, 2, 24, 2]), (b"ffffeeffbb", 47, &[37, 37, 11, 12, 6, 0, 8, 2]), (b"ffffeeffbb", 48, &[11, 41, 40, 43, 5, 43, 41, 1]), (b"ffffeeffbb", 49, &[18, 45, 7, 13, 20, 21, 30, 1]), (b"ffffeeffbb", 50, &[45, 21, 5, 34, 21, 18, 20, 1]), (b"ffffeeffbb", 51, &[17, 6, 26, 22, 38, 24, 11, 1]), (b"ffffeeffbb", 52, &[39, 33, 38, 30, 46, 31, 3, 1]), (b"ffffeeffbb", 53, &[31, 7, 44, 23, 9, 32, 49]), (b"ffffeeffbb", 54, &[17, 35, 8, 37, 31, 18, 44]), (b"ffffeeffbb", 55, &[10, 52, 9, 48, 36, 39, 39]), (b"ffffeeffbb", 56, &[11, 50, 51, 22, 25, 36, 35]), (b"ffffeeffbb", 57, &[14, 55, 12, 43, 20, 3, 32]), (b"ffffeeffbb", 58, &[35, 18, 45, 56, 9, 51, 28]), (b"ffffeeffbb", 59, &[51, 28, 20, 26, 55, 3, 26]), (b"ffffeeffbb", 60, &[35, 6, 27, 46, 58, 33, 23]), (b"ffffeeffbb", 61, &[58, 7, 6, 54, 49, 20, 21]), (b"ffffeeffbb", 62, &[53, 59, 3, 14, 10, 22, 19]), (b"ffffeeffbb", 63, &[53, 50, 23, 4, 56, 36, 17]), (b"ffffeeffbb", 64, &[59, 62, 47, 59, 63, 63, 15]), (b"ffffeeffbb", 65, &[0, 53, 39, 4, 40, 37, 14]), (b"ffffeeffbb", 66, &[65, 59, 39, 1, 64, 19, 13]), (b"ffffeeffbb", 67, &[35, 14, 19, 16, 25, 10, 12]), (b"ffffeeffbb", 68, &[51, 38, 63, 50, 15, 8, 11]), (b"ffffeeffbb", 69, &[44, 45, 18, 58, 68, 12, 10]), (b"ffffeeffbb", 70, &[25, 51, 0, 60, 13, 24, 9]), (b"ffffeeffbb", 71, &[54, 30, 9, 65, 28, 41, 8]), (b"ffffeeffbb", 72, &[35, 35, 55, 54, 17, 64, 7]), (b"ffffeeffbb", 73, &[34, 4, 48, 40, 27, 19, 7]), (b"ffffeeffbb", 74, &[53, 47, 4, 56, 36, 51, 6]), (b"ffffeeffbb", 75, &[20, 56, 10, 72, 24, 13, 6]), (b"ffffeeffbb", 76, &[71, 31, 52, 60, 48, 53, 5]), (b"ffffeeffbb", 77, &[32, 73, 14, 63, 15, 21, 5]), (b"ffffeeffbb", 78, &[65, 13, 17, 32, 64, 68, 4]), (b"ffffeeffbb", 79, &[37, 56, 2, 56, 25, 41, 4]), (b"ffffeeffbb", 80, &[75, 59, 37, 41, 43, 15, 4]), (b"ffffeeffbb", 81, &[44, 68, 0, 21, 27, 72, 3]), (b"ffffeeffbb", 82, &[77, 35, 2, 74, 46, 50, 3]), (b"ffffeeffbb", 83, &[52, 51, 19, 76, 10, 30, 3]), (b"ffffeeffbb", 84, &[11, 80, 19, 19, 76, 10, 3]), (b"ffffeeffbb", 85, &[0, 82, 20, 14, 68, 77, 2]), (b"ffffeeffbb", 86, &[3, 12, 78, 37, 62, 61, 2]), (b"ffffeeffbb", 87, &[35, 12, 20, 8, 52, 46, 2]), (b"ffffeeffbb", 88, &[43, 6, 54, 42, 30, 32, 2]), (b"ffffeeffbb", 89, &[49, 52, 85, 21, 80, 18, 2]), (b"ffffeeffbb", 90, &[35, 64, 78, 24, 18, 6, 2]), (b"ffffeeffbb", 91, &[39, 17, 83, 63, 17, 85, 1]), (b"ffffeeffbb", 92, &[67, 22, 85, 79, 75, 74, 1]), (b"ffffeeffbb", 93, &[53, 60, 39, 29, 4, 65, 1]), (b"ffffeeffbb", 94, &[37, 89, 2, 72, 76, 55, 1]), (b"ffffeeffbb", 95, &[90, 74, 89, 9, 9, 47, 1]), (b"ffffeeffbb", 96, &[59, 20, 46, 35, 81, 38, 1]), (b"ffffeeffbb", 97, &[94, 87, 60, 71, 3, 31, 1]), (b"ffffeeffbb", 98, &[67, 22, 63, 50, 62, 23, 1]), (b"ffffeeffbb", 99, &[98, 6, 69, 12, 61, 16, 1]), (b"ffffeeffbb", 100, &[95, 35, 51, 10, 95, 9, 1]), (b"ffffeeffbb", 101, &[87, 27, 7, 8, 62, 3, 1]), (b"ffffeeffbb", 102, &[17, 3, 32, 79, 59, 99]), (b"ffffeeffbb", 103, &[30, 22, 90, 0, 87, 94]), (b"ffffeeffbb", 104, &[91, 68, 87, 68, 38, 90]), (b"ffffeeffbb", 105, &[95, 80, 54, 73, 15, 86]), (b"ffffeeffbb", 106, &[31, 30, 24, 16, 17, 82]), (b"ffffeeffbb", 107, &[51, 50, 10, 12, 42, 78]), (b"ffffeeffbb", 108, &[71, 71, 96, 78, 89, 74]), (b"ffffeeffbb", 109, &[33, 18, 93, 22, 50, 71]), (b"ffffeeffbb", 110, &[65, 53, 57, 88, 29, 68]), (b"ffffeeffbb", 111, &[53, 93, 67, 90, 27, 65]), (b"ffffeeffbb", 112, &[11, 109, 96, 65, 43, 62]), (b"ffffeeffbb", 113, &[27, 23, 106, 56, 76, 59]), (b"ffffeeffbb", 114, &[71, 84, 31, 112, 11, 57]), (b"ffffeeffbb", 115, &[90, 22, 1, 56, 76, 54]), (b"ffffeeffbb", 116, &[35, 38, 98, 57, 40, 52]), (b"ffffeeffbb", 117, &[26, 113, 115, 62, 17, 50]), (b"ffffeeffbb", 118, &[51, 14, 5, 18, 7, 48]), (b"ffffeeffbb", 119, &[102, 31, 110, 108, 8, 46]), (b"ffffeeffbb", 120, &[35, 93, 96, 50, 22, 44]), (b"ffffeeffbb", 121, &[87, 61, 2, 36, 47, 42]), (b"ffffeeffbb", 122, &[119, 64, 1, 22, 83, 40]), (b"ffffeeffbb", 123, &[77, 119, 32, 90, 6, 39]), (b"ffffeeffbb", 124, &[115, 122, 31, 79, 62, 37]), (b"ffffeeffbb", 125, &[95, 108, 47, 74, 3, 36]), (b"ffffeeffbb", 126, &[53, 25, 116, 39, 78, 34]), (b"ffffeeffbb", 127, &[22, 23, 125, 67, 35, 33]), (b"ffffeeffbb", 128, &[59, 127, 59, 127, 127, 31]), (b"ffffeeffbb", 129, &[89, 36, 1, 59, 100, 30]), (b"ffffeeffbb", 130, &[65, 91, 123, 89, 79, 29]), (b"ffffeeffbb", 131, &[58, 72, 39, 63, 65, 28]), (b"ffffeeffbb", 132, &[131, 62, 92, 82, 57, 27]), (b"ffffeeffbb", 133, &[109, 31, 51, 123, 55, 26]), (b"ffffeeffbb", 134, &[35, 74, 21, 27, 60, 25]), (b"ffffeeffbb", 135, &[125, 132, 49, 37, 70, 24]), (b"ffffeeffbb", 136, &[51, 121, 117, 133, 85, 23]), (b"ffffeeffbb", 137, &[113, 60, 135, 22, 107, 22]), (b"ffffeeffbb", 138, &[113, 91, 73, 93, 133, 21]), (b"ffffeeffbb", 139, &[114, 75, 102, 51, 26, 21]), (b"ffffeeffbb", 140, &[95, 25, 35, 16, 62, 20]), (b"ffffeeffbb", 141, &[131, 137, 16, 110, 102, 19]), (b"ffffeeffbb", 142, &[125, 121, 108, 34, 6, 19]), (b"ffffeeffbb", 143, &[65, 78, 138, 55, 55, 18]), (b"ffffeeffbb", 144, &[107, 125, 121, 15, 109, 17]), (b"ffffeeffbb", 145, &[35, 13, 122, 42, 22, 17]), (b"ffffeeffbb", 146, &[107, 38, 103, 123, 83, 16]), (b"ffffeeffbb", 147, &[116, 96, 71, 98, 2, 16]), (b"ffffeeffbb", 148, &[127, 23, 75, 99, 71, 15]), (b"ffffeeffbb", 149, &[136, 110, 53, 114, 144, 14]), (b"ffffeeffbb", 150, &[95, 140, 133, 130, 71, 14]), (b"ffffeeffbb", 151, &[15, 50, 29, 137, 0, 14]), (b"ffffeeffbb", 152, &[147, 15, 89, 121, 83, 13]), (b"ffffeeffbb", 153, &[17, 87, 93, 72, 17, 13]), (b"ffffeeffbb", 154, &[109, 113, 3, 133, 106, 12]), (b"ffffeeffbb", 155, &[115, 141, 120, 139, 44, 12]), (b"ffffeeffbb", 156, &[143, 45, 4, 82, 140, 11]), (b"ffffeeffbb", 157, &[149, 92, 15, 106, 82, 11]), (b"ffffeeffbb", 158, &[37, 107, 79, 46, 26, 11]), (b"ffffeeffbb", 159, &[137, 37, 146, 51, 130, 10]), (b"ffffeeffbb", 160, &[155, 69, 29, 115, 77, 10]), (b"ffffeeffbb", 161, &[67, 98, 46, 68, 26, 10]), (b"ffffeeffbb", 162, &[125, 155, 60, 63, 138, 9]), (b"ffffeeffbb", 163, &[96, 43, 118, 93, 90, 9]), (b"ffffeeffbb", 164, &[159, 99, 123, 152, 43, 9]), (b"ffffeeffbb", 165, &[65, 17, 1, 69, 163, 8]), (b"ffffeeffbb", 166, &[135, 108, 25, 165, 119, 8]), (b"ffffeeffbb", 167, &[165, 116, 164, 103, 77, 8]), (b"ffffeeffbb", 168, &[11, 166, 67, 44, 36, 8]), (b"ffffeeffbb", 169, &[65, 59, 71, 149, 164, 7]), (b"ffffeeffbb", 170, &[85, 83, 26, 76, 126, 7]), (b"ffffeeffbb", 171, &[71, 132, 140, 157, 88, 7]), (b"ffffeeffbb", 172, &[3, 6, 127, 47, 52, 7]), (b"ffffeeffbb", 173, &[122, 66, 53, 83, 16, 7]), (b"ffffeeffbb", 174, &[35, 6, 5, 88, 155, 6]), (b"ffffeeffbb", 175, &[95, 20, 84, 56, 122, 6]), (b"ffffeeffbb", 176, &[43, 91, 57, 159, 89, 6]), (b"ffffeeffbb", 177, &[110, 127, 54, 40, 58, 6]), (b"ffffeeffbb", 178, &[49, 115, 43, 47, 27, 6]), (b"ffffeeffbb", 179, &[130, 91, 4, 178, 175, 5]), (b"ffffeeffbb", 180, &[35, 122, 109, 70, 147, 5]), (b"ffffeeffbb", 181, &[94, 94, 4, 79, 119, 5]), (b"ffffeeffbb", 182, &[39, 54, 66, 19, 92, 5]), (b"ffffeeffbb", 183, &[119, 2, 143, 69, 65, 5]), (b"ffffeeffbb", 184, &[67, 57, 90, 44, 39, 5]), (b"ffffeeffbb", 185, &[90, 63, 141, 123, 13, 5]), (b"ffffeeffbb", 186, &[53, 123, 172, 119, 174, 4]), (b"ffffeeffbb", 187, &[153, 21, 68, 28, 151, 4]), (b"ffffeeffbb", 188, &[131, 138, 94, 32, 128, 4]), (b"ffffeeffbb", 189, &[179, 121, 156, 130, 105, 4]), (b"ffffeeffbb", 190, &[185, 179, 164, 131, 83, 4]), (b"ffffeeffbb", 191, &[118, 123, 37, 31, 62, 4]), (b"ffffeeffbb", 192, &[59, 106, 83, 16, 41, 4]), (b"ffffeeffbb", 193, &[57, 37, 47, 86, 20, 4]), (b"ffffeeffbb", 194, &[191, 140, 63, 45, 0, 4]), (b"ffffeeffbb", 195, &[65, 169, 83, 84, 175, 3]), (b"ffffeeffbb", 196, &[67, 158, 64, 6, 157, 3]), (b"ffffeeffbb", 197, &[121, 26, 167, 3, 139, 3]), (b"ffffeeffbb", 198, &[197, 151, 165, 75, 121, 3]), (b"ffffeeffbb", 199, &[55, 175, 36, 22, 104, 3]), (b"ffffeeffbb", 200, &[195, 167, 162, 38, 87, 3]), (b"ffffeeffbb", 201, &[35, 27, 136, 124, 70, 3]), (b"ffffeeffbb", 202, &[87, 64, 153, 76, 54, 3]), (b"ffffeeffbb", 203, &[151, 191, 14, 94, 38, 3]), (b"ffffeeffbb", 204, &[119, 103, 135, 175, 22, 3]), (b"ffffeeffbb", 205, &[200, 79, 123, 115, 7, 3]), (b"ffffeeffbb", 206, &[133, 165, 202, 115, 198, 2]), (b"ffffeeffbb", 207, &[44, 153, 193, 175, 184, 2]), (b"ffffeeffbb", 208, &[91, 190, 125, 86, 171, 2]), (b"ffffeeffbb", 209, &[109, 151, 34, 53, 158, 2]), (b"ffffeeffbb", 210, &[95, 40, 171, 74, 145, 2]), (b"ffffeeffbb", 211, &[84, 195, 162, 150, 132, 2]), (b"ffffeeffbb", 212, &[31, 15, 59, 68, 120, 2]), (b"ffffeeffbb", 213, &[125, 57, 127, 36, 108, 2]), (b"ffffeeffbb", 214, &[51, 132, 2, 55, 96, 2]), (b"ffffeeffbb", 215, &[175, 133, 177, 122, 84, 2]), (b"ffffeeffbb", 216, &[179, 35, 78, 23, 73, 2]), (b"ffffeeffbb", 217, &[53, 101, 208, 186, 61, 2]), (b"ffffeeffbb", 218, &[33, 9, 214, 179, 50, 2]), (b"ffffeeffbb", 219, &[107, 147, 175, 217, 39, 2]), (b"ffffeeffbb", 220, &[175, 81, 179, 79, 29, 2]), (b"ffffeeffbb", 221, &[0, 76, 95, 204, 18, 2]), (b"ffffeeffbb", 222, &[53, 213, 16, 150, 8, 2]), (b"ffffeeffbb", 223, &[158, 161, 42, 136, 221, 1]), (b"ffffeeffbb", 224, &[123, 54, 52, 162, 212, 1]), (b"ffffeeffbb", 225, &[170, 43, 151, 2, 204, 1]), (b"ffffeeffbb", 226, &[27, 68, 224, 105, 195, 1]), (b"ffffeeffbb", 227, &[45, 69, 157, 20, 187, 1]), (b"ffffeeffbb", 228, &[71, 213, 64, 199, 178, 1]), (b"ffffeeffbb", 229, &[129, 203, 66, 186, 170, 1]), (b"ffffeeffbb", 230, &[205, 183, 57, 208, 162, 1]), (b"ffffeeffbb", 231, &[32, 50, 164, 33, 155, 1]), (b"ffffeeffbb", 232, &[35, 135, 53, 123, 147, 1]), (b"ffffeeffbb", 233, &[209, 47, 89, 13, 140, 1]), (b"ffffeeffbb", 234, &[143, 56, 175, 168, 132, 1]), (b"ffffeeffbb", 235, &[225, 157, 216, 121, 125, 1]), (b"ffffeeffbb", 236, &[51, 66, 119, 105, 118, 1]), (b"ffffeeffbb", 237, &[116, 150, 26, 119, 111, 1]), (b"ffffeeffbb", 238, &[221, 15, 87, 162, 104, 1]), (b"ffffeeffbb", 239, &[234, 155, 214, 234, 97, 1]), (b"ffffeeffbb", 240, &[155, 46, 84, 96, 91, 1]), (b"ffffeeffbb", 241, &[187, 48, 90, 225, 84, 1]), (b"ffffeeffbb", 242, &[87, 212, 151, 140, 78, 1]), (b"ffffeeffbb", 243, &[206, 22, 189, 81, 72, 1]), (b"ffffeeffbb", 244, &[119, 93, 122, 48, 66, 1]), (b"ffffeeffbb", 245, &[165, 224, 117, 40, 60, 1]), (b"ffffeeffbb", 246, &[77, 121, 100, 57, 54, 1]), (b"ffffeeffbb", 247, &[52, 128, 242, 98, 48, 1]), (b"ffffeeffbb", 248, &[115, 247, 224, 164, 42, 1]), (b"ffffeeffbb", 249, &[218, 127, 223, 5, 37, 1]), (b"ffffeeffbb", 250, &[95, 54, 168, 118, 31, 1]), (b"ffffeeffbb", 251, &[121, 204, 240, 3, 26, 1]), (b"ffffeeffbb", 252, &[179, 138, 123, 162, 20, 1]), (b"ffffeeffbb", 253, &[21, 50, 1, 91, 15, 1]), (b"ffffeeffbb", 254, &[149, 11, 63, 40, 10, 1]), (b"ffffeeffbb", 255, &[170, 225, 247, 9, 5, 1]), (b"ffffeeffbb", 256, &[187, 255, 238, 255, 255]), ]; for &(bigint, radix, inbaseradix_le) in GROUND_TRUTH.iter() { let bigint = BigUint::parse_bytes(bigint, 16).unwrap(); // to_radix_le assert_eq!(bigint.to_radix_le(radix), inbaseradix_le); // to_radix_be let mut inbase_be = bigint.to_radix_be(radix); inbase_be.reverse(); // now le assert_eq!(inbase_be, inbaseradix_le); // from_radix_le assert_eq!( BigUint::from_radix_le(inbaseradix_le, radix).unwrap(), bigint ); // from_radix_be let mut inbaseradix_be = Vec::from(inbaseradix_le); inbaseradix_be.reverse(); assert_eq!( BigUint::from_radix_be(&inbaseradix_be, radix).unwrap(), bigint ); } assert!(BigUint::from_radix_le(&[10, 100, 10], 50).is_none()); } #[test] fn test_from_str_radix() { let r = to_str_pairs(); for num_pair in r.iter() { let &(ref n, ref rs) = num_pair; for str_pair in rs.iter() { let &(ref radix, ref str) = str_pair; assert_eq!(n, &BigUint::from_str_radix(str, *radix).unwrap()); } } let zed = BigUint::from_str_radix("Z", 10).ok(); assert_eq!(zed, None); let blank = BigUint::from_str_radix("_", 2).ok(); assert_eq!(blank, None); let blank_one = BigUint::from_str_radix("_1", 2).ok(); assert_eq!(blank_one, None); let plus_one = BigUint::from_str_radix("+1", 10).ok(); assert_eq!(plus_one, Some(BigUint::from_slice(&[1]))); let plus_plus_one = BigUint::from_str_radix("++1", 10).ok(); assert_eq!(plus_plus_one, None); let minus_one = BigUint::from_str_radix("-1", 10).ok(); assert_eq!(minus_one, None); let zero_plus_two = BigUint::from_str_radix("0+2", 10).ok(); assert_eq!(zero_plus_two, None); let three = BigUint::from_str_radix("1_1", 2).ok(); assert_eq!(three, Some(BigUint::from_slice(&[3]))); let ff = BigUint::from_str_radix("1111_1111", 2).ok(); assert_eq!(ff, Some(BigUint::from_slice(&[0xff]))); } #[test] fn test_all_str_radix() { #[allow(deprecated, unused_imports)] use std::ascii::AsciiExt; let n = BigUint::new((0..10).collect()); for radix in 2..37 { let s = n.to_str_radix(radix); let x = BigUint::from_str_radix(&s, radix); assert_eq!(x.unwrap(), n); let s = s.to_ascii_uppercase(); let x = BigUint::from_str_radix(&s, radix); assert_eq!(x.unwrap(), n); } } #[test] fn test_lower_hex() { let a = BigUint::parse_bytes(b"A", 16).unwrap(); let hello = BigUint::parse_bytes("22405534230753963835153736737".as_bytes(), 10).unwrap(); assert_eq!(format!("{:x}", a), "a"); assert_eq!(format!("{:x}", hello), "48656c6c6f20776f726c6421"); assert_eq!(format!("{:♥>+#8x}", a), "♥♥♥♥+0xa"); } #[test] fn test_upper_hex() { let a = BigUint::parse_bytes(b"A", 16).unwrap(); let hello = BigUint::parse_bytes("22405534230753963835153736737".as_bytes(), 10).unwrap(); assert_eq!(format!("{:X}", a), "A"); assert_eq!(format!("{:X}", hello), "48656C6C6F20776F726C6421"); assert_eq!(format!("{:♥>+#8X}", a), "♥♥♥♥+0xA"); } #[test] fn test_binary() { let a = BigUint::parse_bytes(b"A", 16).unwrap(); let hello = BigUint::parse_bytes("224055342307539".as_bytes(), 10).unwrap(); assert_eq!(format!("{:b}", a), "1010"); assert_eq!( format!("{:b}", hello), "110010111100011011110011000101101001100011010011" ); assert_eq!(format!("{:♥>+#8b}", a), "♥+0b1010"); } #[test] fn test_octal() { let a = BigUint::parse_bytes(b"A", 16).unwrap(); let hello = BigUint::parse_bytes("22405534230753963835153736737".as_bytes(), 10).unwrap(); assert_eq!(format!("{:o}", a), "12"); assert_eq!(format!("{:o}", hello), "22062554330674403566756233062041"); assert_eq!(format!("{:♥>+#8o}", a), "♥♥♥+0o12"); } #[test] fn test_display() { let a = BigUint::parse_bytes(b"A", 16).unwrap(); let hello = BigUint::parse_bytes("22405534230753963835153736737".as_bytes(), 10).unwrap(); assert_eq!(format!("{}", a), "10"); assert_eq!(format!("{}", hello), "22405534230753963835153736737"); assert_eq!(format!("{:♥>+#8}", a), "♥♥♥♥♥+10"); } #[test] fn test_factor() { fn factor(n: usize) -> BigUint { let mut f: BigUint = One::one(); for i in 2..n + 1 { // FIXME(#5992): assignment operator overloads // f *= FromPrimitive::from_usize(i); let bu: BigUint = FromPrimitive::from_usize(i).unwrap(); f = f * bu; } return f; } fn check(n: usize, s: &str) { let n = factor(n); let ans = match BigUint::from_str_radix(s, 10) { Ok(x) => x, Err(_) => panic!(), }; assert_eq!(n, ans); } check(3, "6"); check(10, "3628800"); check(20, "2432902008176640000"); check(30, "265252859812191058636308480000000"); } #[test] fn test_bits() { assert_eq!(BigUint::new(vec![0, 0, 0, 0]).bits(), 0); let n: BigUint = FromPrimitive::from_usize(0).unwrap(); assert_eq!(n.bits(), 0); let n: BigUint = FromPrimitive::from_usize(1).unwrap(); assert_eq!(n.bits(), 1); let n: BigUint = FromPrimitive::from_usize(3).unwrap(); assert_eq!(n.bits(), 2); let n: BigUint = BigUint::from_str_radix("4000000000", 16).unwrap(); assert_eq!(n.bits(), 39); let one: BigUint = One::one(); assert_eq!((one << 426).bits(), 427); } #[test] fn test_iter_sum() { let result: BigUint = FromPrimitive::from_isize(1234567).unwrap(); let data: Vec = vec![ FromPrimitive::from_u32(1000000).unwrap(), FromPrimitive::from_u32(200000).unwrap(), FromPrimitive::from_u32(30000).unwrap(), FromPrimitive::from_u32(4000).unwrap(), FromPrimitive::from_u32(500).unwrap(), FromPrimitive::from_u32(60).unwrap(), FromPrimitive::from_u32(7).unwrap(), ]; assert_eq!(result, data.iter().sum()); assert_eq!(result, data.into_iter().sum()); } #[test] fn test_iter_product() { let data: Vec = vec![ FromPrimitive::from_u32(1001).unwrap(), FromPrimitive::from_u32(1002).unwrap(), FromPrimitive::from_u32(1003).unwrap(), FromPrimitive::from_u32(1004).unwrap(), FromPrimitive::from_u32(1005).unwrap(), ]; let result = data.get(0).unwrap() * data.get(1).unwrap() * data.get(2).unwrap() * data.get(3).unwrap() * data.get(4).unwrap(); assert_eq!(result, data.iter().product()); assert_eq!(result, data.into_iter().product()); } #[test] fn test_iter_sum_generic() { let result: BigUint = FromPrimitive::from_isize(1234567).unwrap(); let data = vec![1000000_u32, 200000, 30000, 4000, 500, 60, 7]; assert_eq!(result, data.iter().sum()); assert_eq!(result, data.into_iter().sum()); } #[test] fn test_iter_product_generic() { let data = vec![1001_u32, 1002, 1003, 1004, 1005]; let result = data[0].to_biguint().unwrap() * data[1].to_biguint().unwrap() * data[2].to_biguint().unwrap() * data[3].to_biguint().unwrap() * data[4].to_biguint().unwrap(); assert_eq!(result, data.iter().product()); assert_eq!(result, data.into_iter().product()); } #[test] fn test_pow() { let one = BigUint::from(1u32); let two = BigUint::from(2u32); let four = BigUint::from(4u32); let eight = BigUint::from(8u32); let tentwentyfour = BigUint::from(1024u32); let twentyfourtyeight = BigUint::from(2048u32); macro_rules! check { ($t:ty) => { assert_eq!(two.pow(0 as $t), one); assert_eq!(two.pow(1 as $t), two); assert_eq!(two.pow(2 as $t), four); assert_eq!(two.pow(3 as $t), eight); assert_eq!(two.pow(10 as $t), tentwentyfour); assert_eq!(two.pow(11 as $t), twentyfourtyeight); assert_eq!(two.pow(&(11 as $t)), twentyfourtyeight); }; } check!(u8); check!(u16); check!(u32); check!(u64); check!(usize); #[cfg(has_i128)] check!(u128); } num-bigint-dig-0.8.2/tests/biguint_scalar.rs000064400000000000000000000052541046102023000171510ustar 00000000000000extern crate num_bigint_dig as num_bigint; extern crate num_traits; use crate::num_bigint::BigUint; use num_traits::{ToPrimitive, Zero}; mod consts; use crate::consts::*; #[macro_use] mod macros; #[test] fn test_scalar_add() { fn check(x: &BigUint, y: &BigUint, z: &BigUint) { let (x, y, z) = (x.clone(), y.clone(), z.clone()); assert_unsigned_scalar_op!(x + y == z); } for elm in SUM_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); let c = BigUint::from_slice(c_vec); check(&a, &b, &c); check(&b, &a, &c); } } #[test] fn test_scalar_sub() { fn check(x: &BigUint, y: &BigUint, z: &BigUint) { let (x, y, z) = (x.clone(), y.clone(), z.clone()); assert_unsigned_scalar_op!(x - y == z); } for elm in SUM_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); let c = BigUint::from_slice(c_vec); check(&c, &a, &b); check(&c, &b, &a); } } #[test] fn test_scalar_mul() { fn check(x: &BigUint, y: &BigUint, z: &BigUint) { let (x, y, z) = (x.clone(), y.clone(), z.clone()); assert_unsigned_scalar_op!(x * y == z); } for elm in MUL_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); let c = BigUint::from_slice(c_vec); check(&a, &b, &c); check(&b, &a, &c); } } #[test] fn test_scalar_div_rem() { fn check(x: &BigUint, y: &BigUint, z: &BigUint, r: &BigUint) { let (x, y, z, r) = (x.clone(), y.clone(), z.clone(), r.clone()); assert_unsigned_scalar_op!(x / y == z); assert_unsigned_scalar_op!(x % y == r); } for elm in MUL_TRIPLES.iter() { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); let c = BigUint::from_slice(c_vec); if !a.is_zero() { check(&c, &a, &b, &Zero::zero()); } if !b.is_zero() { check(&c, &b, &a, &Zero::zero()); } } for elm in DIV_REM_QUADRUPLES.iter() { let (a_vec, b_vec, c_vec, d_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); let c = BigUint::from_slice(c_vec); let d = BigUint::from_slice(d_vec); if !b.is_zero() { check(&a, &b, &c, &d); assert_unsigned_scalar_op!(a / b == c); assert_unsigned_scalar_op!(a % b == d); } } } num-bigint-dig-0.8.2/tests/consts/mod.rs000064400000000000000000000034441046102023000162520ustar 00000000000000#![allow(unused)] pub const N1: u32 = -1i32 as u32; pub const N2: u32 = -2i32 as u32; pub const SUM_TRIPLES: &'static [(&'static [u32], &'static [u32], &'static [u32])] = &[ (&[], &[], &[]), (&[], &[1], &[1]), (&[1], &[1], &[2]), (&[1], &[1, 1], &[2, 1]), (&[1], &[N1], &[0, 1]), (&[1], &[N1, N1], &[0, 0, 1]), (&[N1, N1], &[N1, N1], &[N2, N1, 1]), (&[1, 1, 1], &[N1, N1], &[0, 1, 2]), (&[2, 2, 1], &[N1, N2], &[1, 1, 2]), (&[1, 2, 2, 1], &[N1, N2], &[0, 1, 3, 1]), ]; pub const M: u32 = ::std::u32::MAX; pub const MUL_TRIPLES: &'static [(&'static [u32], &'static [u32], &'static [u32])] = &[ (&[], &[], &[]), (&[], &[1], &[]), (&[2], &[], &[]), (&[1], &[1], &[1]), (&[2], &[3], &[6]), (&[1], &[1, 1, 1], &[1, 1, 1]), (&[1, 2, 3], &[3], &[3, 6, 9]), (&[1, 1, 1], &[N1], &[N1, N1, N1]), (&[1, 2, 3], &[N1], &[N1, N2, N2, 2]), (&[1, 2, 3, 4], &[N1], &[N1, N2, N2, N2, 3]), (&[N1], &[N1], &[1, N2]), (&[N1, N1], &[N1], &[1, N1, N2]), (&[N1, N1, N1], &[N1], &[1, N1, N1, N2]), (&[N1, N1, N1, N1], &[N1], &[1, N1, N1, N1, N2]), (&[M / 2 + 1], &[2], &[0, 1]), (&[0, M / 2 + 1], &[2], &[0, 0, 1]), (&[1, 2], &[1, 2, 3], &[1, 4, 7, 6]), (&[N1, N1], &[N1, N1, N1], &[1, 0, N1, N2, N1]), (&[N1, N1, N1], &[N1, N1, N1, N1], &[1, 0, 0, N1, N2, N1, N1]), (&[0, 0, 1], &[1, 2, 3], &[0, 0, 1, 2, 3]), (&[0, 0, 1], &[0, 0, 0, 1], &[0, 0, 0, 0, 0, 1]), ]; pub const DIV_REM_QUADRUPLES: &'static [( &'static [u32], &'static [u32], &'static [u32], &'static [u32], )] = &[ (&[1], &[2], &[], &[1]), (&[3], &[2], &[1], &[1]), (&[1, 1], &[2], &[M / 2 + 1], &[1]), (&[1, 1, 1], &[2], &[M / 2 + 1, M / 2 + 1], &[1]), (&[0, 1], &[N1], &[1], &[1]), (&[N1, N1], &[N2], &[2, 1], &[3]), ]; num-bigint-dig-0.8.2/tests/macros/mod.rs000064400000000000000000000045421046102023000162250ustar 00000000000000#![allow(unused)] /// Assert that an op works for all val/ref combinations macro_rules! assert_op { ($left:ident $op:tt $right:ident == $expected:expr) => { assert_eq!((&$left) $op (&$right), $expected); assert_eq!((&$left) $op $right.clone(), $expected); assert_eq!($left.clone() $op (&$right), $expected); assert_eq!($left.clone() $op $right.clone(), $expected); }; } /// Assert that an assign-op works for all val/ref combinations macro_rules! assert_assign_op { ($left:ident $op:tt $right:ident == $expected:expr) => {{ let mut left = $left.clone(); assert_eq!({ left $op &$right; left}, $expected); let mut left = $left.clone(); assert_eq!({ left $op $right.clone(); left}, $expected); }}; } /// Assert that an op works for scalar left or right macro_rules! assert_scalar_op { (($($to:ident),*) $left:ident $op:tt $right:ident == $expected:expr) => { $( if let Some(left) = $left.$to() { assert_op!(left $op $right == $expected); } if let Some(right) = $right.$to() { assert_op!($left $op right == $expected); } )* }; } #[cfg(not(has_i128))] macro_rules! assert_unsigned_scalar_op { ($left:ident $op:tt $right:ident == $expected:expr) => { assert_scalar_op!((to_u8, to_u16, to_u32, to_u64, to_usize) $left $op $right == $expected); }; } #[cfg(has_i128)] macro_rules! assert_unsigned_scalar_op { ($left:ident $op:tt $right:ident == $expected:expr) => { assert_scalar_op!((to_u8, to_u16, to_u32, to_u64, to_usize, to_u128) $left $op $right == $expected); }; } #[cfg(not(has_i128))] macro_rules! assert_signed_scalar_op { ($left:ident $op:tt $right:ident == $expected:expr) => { assert_scalar_op!((to_u8, to_u16, to_u32, to_u64, to_usize, to_i8, to_i16, to_i32, to_i64, to_isize) $left $op $right == $expected); }; } #[cfg(has_i128)] macro_rules! assert_signed_scalar_op { ($left:ident $op:tt $right:ident == $expected:expr) => { assert_scalar_op!((to_u8, to_u16, to_u32, to_u64, to_usize, to_u128, to_i8, to_i16, to_i32, to_i64, to_isize, to_i128) $left $op $right == $expected); }; } num-bigint-dig-0.8.2/tests/modpow.rs000064400000000000000000000403631046102023000154700ustar 00000000000000extern crate num_bigint_dig as num_bigint; extern crate num_integer; extern crate num_traits; static BIG_B: &'static str = "\ efac3c0a_0de55551_fee0bfe4_67fa017a_1a898fa1_6ca57cb1\ ca9e3248_cacc09a9_b99d6abc_38418d0f_82ae4238_d9a68832\ aadec7c1_ac5fed48_7a56a71b_67ac59d5_afb28022_20d9592d\ 247c4efc_abbd9b75_586088ee_1dc00dc4_232a8e15_6e8191dd\ 675b6ae0_c80f5164_752940bc_284b7cee_885c1e10_e495345b\ 8fbe9cfd_e5233fe1_19459d0b_d64be53c_27de5a02_a829976b\ 33096862_82dad291_bd38b6a9_be396646_ddaf8039_a2573c39\ 1b14e8bc_2cb53e48_298c047e_d9879e9c_5a521076_f0e27df3\ 990e1659_d3d8205b_6443ebc0_9918ebee_6764f668_9f2b2be3\ b59cbc76_d76d0dfc_d737c3ec_0ccf9c00_ad0554bf_17e776ad\ b4edf9cc_6ce540be_76229093_5c53893b"; static BIG_E: &'static str = "\ be0e6ea6_08746133_e0fbc1bf_82dba91e_e2b56231_a81888d2\ a833a1fc_f7ff002a_3c486a13_4f420bf3_a5435be9_1a5c8391\ 774d6e6c_085d8357_b0c97d4d_2bb33f7c_34c68059_f78d2541\ eacc8832_426f1816_d3be001e_b69f9242_51c7708e_e10efe98\ 449c9a4a_b55a0f23_9d797410_515da00d_3ea07970_4478a2ca\ c3d5043c_bd9be1b4_6dce479d_4302d344_84a939e6_0ab5ada7\ 12ae34b2_30cc473c_9f8ee69d_2cac5970_29f5bf18_bc8203e4\ f3e895a2_13c94f1e_24c73d77_e517e801_53661fdd_a2ce9e47\ a73dd7f8_2f2adb1e_3f136bf7_8ae5f3b8_08730de1_a4eff678\ e77a06d0_19a522eb_cbefba2a_9caf7736_b157c5c6_2d192591\ 17946850_2ddb1822_117b68a0_32f7db88"; // This modulus is the prime from the 2048-bit MODP DH group: // https://tools.ietf.org/html/rfc3526#section-3 static BIG_M: &'static str = "\ FFFFFFFF_FFFFFFFF_C90FDAA2_2168C234_C4C6628B_80DC1CD1\ 29024E08_8A67CC74_020BBEA6_3B139B22_514A0879_8E3404DD\ EF9519B3_CD3A431B_302B0A6D_F25F1437_4FE1356D_6D51C245\ E485B576_625E7EC6_F44C42E9_A637ED6B_0BFF5CB6_F406B7ED\ EE386BFB_5A899FA5_AE9F2411_7C4B1FE6_49286651_ECE45B3D\ C2007CB8_A163BF05_98DA4836_1C55D39A_69163FA8_FD24CF5F\ 83655D23_DCA3AD96_1C62F356_208552BB_9ED52907_7096966D\ 670C354E_4ABC9804_F1746C08_CA18217C_32905E46_2E36CE3B\ E39E772C_180E8603_9B2783A2_EC07A28F_B5C55DF0_6F4C52C9\ DE2BCBF6_95581718_3995497C_EA956AE5_15D22618_98FA0510\ 15728E5A_8AACAA68_FFFFFFFF_FFFFFFFF"; static BIG_R: &'static str = "\ a1468311_6e56edc9_7a98228b_5e924776_0dd7836e_caabac13\ eda5373b_4752aa65_a1454850_40dc770e_30aa8675_6be7d3a8\ 9d3085e4_da5155cf_b451ef62_54d0da61_cf2b2c87_f495e096\ 055309f7_77802bbb_37271ba8_1313f1b5_075c75d1_024b6c77\ fdb56f17_b05bce61_e527ebfd_2ee86860_e9907066_edd526e7\ 93d289bf_6726b293_41b0de24_eff82424_8dfd374b_4ec59542\ 35ced2b2_6b195c90_10042ffb_8f58ce21_bc10ec42_64fda779\ d352d234_3d4eaea6_a86111ad_a37e9555_43ca78ce_2885bed7\ 5a30d182_f1cf6834_dc5b6e27_1a41ac34_a2e91e11_33363ff0\ f88a7b04_900227c9_f6e6d06b_7856b4bb_4e354d61_060db6c8\ 109c4735_6e7db425_7b5d74c7_0b709508"; mod biguint { use crate::num_bigint::BigUint; use num_integer::Integer; use num_traits::Num; fn check_modpow>(b: T, e: T, m: T, r: T) { let b: BigUint = b.into(); let e: BigUint = e.into(); let m: BigUint = m.into(); let r: BigUint = r.into(); assert_eq!(b.modpow(&e, &m), r); let even_m = &m << 1; let even_modpow = b.modpow(&e, &even_m); assert!(even_modpow < even_m); assert_eq!(even_modpow.mod_floor(&m), r); } #[test] fn test_modpow_single() { check_modpow::(1, 0, 11, 1); check_modpow::(0, 15, 11, 0); check_modpow::(3, 7, 11, 9); check_modpow::(5, 117, 19, 1); } #[test] fn test_modpow_big() { let b = BigUint::from_str_radix(super::BIG_B, 16).unwrap(); let e = BigUint::from_str_radix(super::BIG_E, 16).unwrap(); let m = BigUint::from_str_radix(super::BIG_M, 16).unwrap(); let r = BigUint::from_str_radix(super::BIG_R, 16).unwrap(); assert_eq!(b.modpow(&e, &m), r); let even_m = &m << 1; let even_modpow = b.modpow(&e, &even_m); assert!(even_modpow < even_m); assert_eq!(even_modpow % m, r); } } mod bigint { use crate::num_bigint::BigInt; use num_integer::Integer; use num_traits::{Num, One, Signed, Zero}; fn check_modpow>(b: T, e: T, m: T, r: T) { fn check(b: &BigInt, e: &BigInt, m: &BigInt, r: &BigInt) { assert_eq!(&b.modpow(e, m), r, "{} ** {} (mod {}) != {}", b, e, m, r); let even_m = m << 1; let even_modpow = b.modpow(e, m); assert!(even_modpow.abs() < even_m.abs()); assert_eq!(&even_modpow.mod_floor(&m), r); // the sign of the result follows the modulus like `mod_floor`, not `rem` assert_eq!(b.modpow(&BigInt::one(), m), b.mod_floor(m)); } let b: BigInt = b.into(); let e: BigInt = e.into(); let m: BigInt = m.into(); let r: BigInt = r.into(); let neg_r = if r.is_zero() { BigInt::zero() } else { &m - &r }; check(&b, &e, &m, &r); check(&-&b, &e, &m, &neg_r); check(&b, &e, &-&m, &-neg_r); check(&-b, &e, &-m, &-r); } #[test] fn test_modpow() { check_modpow(1, 0, 11, 1); check_modpow(0, 15, 11, 0); check_modpow(3, 7, 11, 9); check_modpow(5, 117, 19, 1); } #[test] fn test_modpow_big() { let b = BigInt::from_str_radix(super::BIG_B, 16).unwrap(); let e = BigInt::from_str_radix(super::BIG_E, 16).unwrap(); let m = BigInt::from_str_radix(super::BIG_M, 16).unwrap(); let r = BigInt::from_str_radix(super::BIG_R, 16).unwrap(); check_modpow(b, e, m, r); } #[test] fn test_modpow_regressions() { let b = BigInt::from_str_radix("148481812629898028922243452517931778859", 10).unwrap(); let e = BigInt::from_str_radix("164350981728398375121965168123110934994905698786703672972672898604245122565384632665320229592664080184165678526847345884979164161361870788392677397259783361669997458210059361790185938355877563593929478714825040836748164957314359093451997607971771611547549257793609195252376766141281726486479115003799144714128183665696714578467393814120227526482585239840445787567632354733951957802345386715871248483047881497956525866247944829277967526068822788411625449554600640196891378473177802068346095758817143275166167483977379612377628733368341719053305460274294511350837763626861228995578887259487962243311935062225921128133638312621437945519992818288453465098708801352407433629892022649558518668739019522985290473827609521712606998009402034024115903168144255768042129320865368708422779323482567497680433767646272900161006545330040104288222657772869086562080890990921279729840054238397946649195066553267786045462193245099006103846313224069126654860364743773661528709159184162331890246026968468075854895004614440562563403966571088898841287746465509970812429808338370105314308176865461375659159994405123891266709337612303317811367850519031055517613606059551539655265079163631883411122545335469009188561490562340100241858667397070522833201378945082367080303930737460085913589781310332202843084405789975523360515518724292604959852907884723834109301037010981810400469821789426150300238378910637164951422912400649144069581318797904885229033199330969917473583627360277003209342444115817442334409699908719803971129585552217720163472715197434582192016473415220486410376364470209613934593616891157837722052159595619082131329052418471178979749070210646603488411877432337686669419064020146677994675645890784629031645629931044021516402055317993934721616608563696148934577409311708245083906757791103637690292510165547063401385527997056954121665477882557077292209554459496917982492339487229688141530763150692622623272795444529846010384212201717448354354471390313394944641420537729794077616571212880759114553942399699567974275501943806450519656537154820877876153351290438129999404025460264150569923247671803347738438612339550712022372942743592714754306573808282605717032033275819875343175553669801881988323385785362441046181380541210414863721994233865976156241919018538304838096986853747426670289401018164419516853632768820383362107004227976035106131118469545950224360356987548199429365053752748081699631233511074051178296391097574448304825464270687816512317401375349484673480301886627859649660082713607771750803606946084699744123429385446074215481141415144959640495628130348624468766836381762042510936781300722486115488063326027291451024039766392335908184086768228847596527550616790205674080213548408229763037392340969472676595602270556401071384048020604327909934501565252293793797207146346237353181180650897635078348651682864682545684947006709194254396944396423192353225297735761017692031892010530886940052190428897070608145423884897961731293039683402223509642109932203493243263084842325764879968428129677259371460792715707895715737224078949761353247616162380061037191950050487463467812528656164400320234629304223345519745970775250821617679739209663950777506253481666213838435163785552701719451996405973898572946407314707644934778581322359906640869284294008054618184044944168077716469330553710607919475086198736822731411106767940517513117067340920713956504198958381975020396473042592923524697202199789614266606522684257572874995317955495218327193196753831545046930031947998147927851349772167106931459070942284239583716608592952560598540897287777232908661009153651601604269678247020505664949407134130455848520117547622541906732872100446640944626050064890054058389328759836051637590769709964190451361835977224657258154841427245128343914641758799690579706226595910843566133142399343803084018750765024209423758381252111340434598457630441263172401042037129339512480216561859237485485179316642715257798126649381183656694101241603952597449444909120197153522721490913694897355020355204849405171656334281390879810015575579384526915097294240353667407269558059437125234100571601655058663167086384390197946929355280399788013937609353436082888066756321802952215535926645873241527518339318793147919520660517850111074815282027596328391301608794376252865467079832695530445147672411416273240414437731626856569247968458705303971664831520406276181645211389639682423522154589153857862875820332977990620041874779912534487054875146227333182840793848696822083435299675425290586091746886253719376517376476192979085056002906185495241899325295106611248170270201999129505310823968875198192620688215223646536583263434182903541968689220812272083266201543646730605107614994880972852396541610915266940027186999857045792946342509904360006232236385410875003200003710271753907829437379680408328394065483143578396887566566005407578049525700830381650375391369588237592292574983213859202661428243174328514293270384618273277544583385984487503069129233267053646486572518591625604138011396668605361469032350603582888850778247186965442140444404195860308517896349031637246734945680372839546785278479593824257340527474351027861885392290231378838449725230480694930523008277023154555844343297155030642104598551668450374495246522115798459878558197309686627849547255201282303229719213831030170763906878819183484135468001583820625287461250511735890029467608943110965462084671268661889450052241131060465481175469285658052200025128774690538495390259618074262588140655147228805545049873691855054152255770202829440165503982450624005234795768600340087204677562163377727571121882970611075470502776106556822809472703656347295866746124605204135016829660149143986183668195830353797312832360933413687525614207287013489308257746670458517988651073504753625204959605466094771204209964965541710217080544310915210188893650613899394914870323514246198819988568145291383437326992546113583363899966403356219181683992559908962490561664206795233711792893981773521595699751343042228013932508198601083950252622077065636311291522313149517311977225604486651761581102311245044441267458710690116324603014332726884757767675055064026627538150429094284462465936700805774875213555790247688992265287670483674835359537320362066496631237532066434198486983108134077101914489258787273151097982046578991716153170761170565232354349286283062140146535745514689289849445004028675192230268395088320480288024809248753472669586551981632827331574644655254527360946541171694009094534525965788372249561700117566619377612607784622980162705615061563640861523841144853582789547670660998574405213291156583471422472737024713335911128552519494928220447015458117896038528532736249462994191693731924310038783792155090734024701098844694228302557144109939199656035117618815047127207778455632893493029828318966843557912588160243215378697136562712636447184586542592233327626401267509598734844522240759857137220876909047828060336559766882884056292087298828311843464955622703622199634508141793685859364925637793777682016420351323859848010606623465396948369240631276472572232028281297280828901171208847997385162695745049130595743829108979357004406444046586221335176301152731273434672154904521807542045622667736615188377717166157412872030872463207532820694823277895456126315590200107172399501418780662873848899945555090581629304192293210512166806174241905318439297836572429492555945848426574436820804276431938356677265173902567516974372557048005931467724243514313618168555104937201562664655492712786862271369422893595407516698240054274482308875406045004002766861865486805088644548951780356707149274987632240062289750700451450662820311466431667428284851948473650031507800214161385241719742922217838238400711647126794748806174836882883940057722793324676878558204321525826413953232881576775548034368728022937081394740112688238217301103514009488899854828922756909485766733545511482058947421794810707669182386862066862732498731756283370966668219295546440670559968588114589890542419364782206557895743456359437472986220063749869820539379941257862675002615164658188357798105487865311641962685185181852938728255920848800712212039448123892624090215049822390599899936382039234469555489723925532717532999939422880433214314964121376053233983116473767598132603437846016981354171586132813499569707397461677048841971510919245413813114311724904074380969238678296194626059869912965335551790872571048158053224153865323110852167314493276323090198653641172199104636190926118630451555110729692658524817414978729750372126722731500043191633465954497667185630804110549483087599351274519782412871406368481080021704006725857372058573865218993668019024024208275108900357152765961057292140846117515718034378698161351291158047506515803497515956519959532767226029329927621693742244108404900014394147196418357662166818493187358701629972155595893579939701750218259082071634738306600756059735100899792211287340114305538026232183669968800789674455430940867429885716527243860641947991536204288665082058524860060114668806790606990321001884609501157240809649183919063321158567912329113896832740889245598107417790596778129724526582814454491169202690995589063942376974544174226050004223359926067502761530455570619313444306185650028516198954161354984900397079331598983284892569733533525469198148807066556718513506092297233405158834932205982055789299794670101612866721906061130211546399655425605752494047788017152677453616235600992059935426874231748721437691974116227927409158423042936833609068849541189", 10).unwrap(); let m = BigInt::from_str_radix("243440964008985994185807471607210276717", 10).unwrap(); let r = BigInt::from_str_radix("138995801145388806366366393471481216294", 10).unwrap(); check_modpow(b, e, m, r); } } num-bigint-dig-0.8.2/tests/rand.rs000064400000000000000000000346071046102023000151130ustar 00000000000000#![cfg(feature = "rand")] extern crate num_bigint_dig as num_bigint; extern crate num_traits; extern crate rand; extern crate rand_chacha; extern crate rand_isaac; extern crate rand_xorshift; mod biguint { use crate::num_bigint::{BigUint, RandBigInt, RandomBits}; use num_traits::Zero; use rand::distributions::Uniform; use rand::{Rng, SeedableRng}; #[cfg(feature = "std")] fn thread_rng() -> impl Rng { rand::thread_rng() } #[cfg(not(feature = "std"))] fn thread_rng() -> impl Rng { // Chosen by fair dice roll rand::rngs::StdRng::seed_from_u64(4) } #[test] fn test_rand() { let mut rng = thread_rng(); let n: BigUint = rng.gen_biguint(137); assert!(n.bits() <= 137); assert!(rng.gen_biguint(0).is_zero()); } #[test] fn test_rand_bits() { let mut rng = thread_rng(); let n: BigUint = rng.sample(&RandomBits::new(137)); assert!(n.bits() <= 137); let z: BigUint = rng.sample(&RandomBits::new(0)); assert!(z.is_zero()); } #[test] fn test_rand_range() { let mut rng = thread_rng(); for _ in 0..10 { assert_eq!( rng.gen_biguint_range(&BigUint::from(236u32), &BigUint::from(237u32)), BigUint::from(236u32) ); } let l = BigUint::from(403469000u32 + 2352); let u = BigUint::from(403469000u32 + 3513); for _ in 0..1000 { let n: BigUint = rng.gen_biguint_below(&u); assert!(n < u); let n: BigUint = rng.gen_biguint_range(&l, &u); assert!(n >= l); assert!(n < u); } } #[test] #[should_panic] fn test_zero_rand_range() { thread_rng().gen_biguint_range(&BigUint::from(54u32), &BigUint::from(54u32)); } #[test] #[should_panic] fn test_negative_rand_range() { let mut rng = thread_rng(); let l = BigUint::from(2352u32); let u = BigUint::from(3513u32); // Switching u and l should fail: let _n: BigUint = rng.gen_biguint_range(&u, &l); } #[test] fn test_rand_uniform() { let mut rng = thread_rng(); let tiny = Uniform::new(BigUint::from(236u32), BigUint::from(237u32)); for _ in 0..10 { assert_eq!(rng.sample(&tiny), BigUint::from(236u32)); } let l = BigUint::from(403469000u32 + 2352); let u = BigUint::from(403469000u32 + 3513); let below = Uniform::new(BigUint::zero(), u.clone()); let range = Uniform::new(l.clone(), u.clone()); for _ in 0..1000 { let n: BigUint = rng.sample(&below); assert!(n < u); let n: BigUint = rng.sample(&range); assert!(n >= l); assert!(n < u); } } fn seeded_value_stability(expected: &[&str]) { let mut seed = ::default(); for (i, x) in seed.as_mut().iter_mut().enumerate() { *x = (i as u8).wrapping_mul(191); } let mut rng = R::from_seed(seed); for (i, &s) in expected.iter().enumerate() { let n: BigUint = s.parse().unwrap(); let r = rng.gen_biguint((1 << i) + i); assert_eq!(n, r, "expected {}, got {}", n, r); } } #[cfg(not(feature = "u64_digit"))] const EXPECTED_CHACHA: &[&str] = &[ "0", "0", "52", "84", "23780", "86502865016", "187057847319509867386", "34045731223080904464438757488196244981910", "23813754422987836414755953516143692594193066497413249270287126597896871975915808", "57401636903146945411652549098818446911814352529449356393690984105383482703074355\ 67088360974672291353736011718191813678720755501317478656550386324355699624671", ]; #[cfg(feature = "u64_digit")] const EXPECTED_CHACHA: &[&str] = &[ "0", "0", "8", "1861", "172076", "5194801951", "259202797457072892019", "2806086822955830608275100562233284760859", "28771276448190704455825316568337256462972770861366848469339788407170414346460023", "501572804396703231264118826164515310701005506447150057229826006447721882571235378\ 4765127362270091441643338804096337494157874113908470083557122824480944132407", ]; #[test] fn test_chacha_value_stability() { use rand_chacha::ChaChaRng; seeded_value_stability::(EXPECTED_CHACHA); } #[cfg(not(feature = "u64_digit"))] const EXPECTED_ISAAC: &[&str] = &[ "1", "4", "3", "649", "89116", "7730042024", "20773149082453254949", "35999009049239918667571895439206839620281", "10191757312714088681302309313551624007714035309632506837271600807524767413673006", "37805949268912387809989378008822038725134260145886913321084097194957861133272558\ 43458183365174899239251448892645546322463253898288141861183340823194379722556", ]; #[cfg(feature = "u64_digit")] const EXPECTED_ISAAC: &[&str] = &[ "1", "2", "51", "1198", "29707", "35688018574", "365090200586541225112", "14051533166427520604648370582738617763816", "26319846996091585801307964353534339679417889504909644767909019559631059772127122", "14567336733062747693583250833667292276083519237160662196899060257293814346680656\ 30951609693408423310563908301065751714778956255122249041917698392245727713420", ]; #[test] fn test_isaac_value_stability() { use rand_isaac::IsaacRng; seeded_value_stability::(EXPECTED_ISAAC); } #[cfg(not(feature = "u64_digit"))] const EXPECTED_XOR: &[&str] = &[ "1", "0", "37", "395", "181116", "122718231117", "1068467172329355695001", "28246925743544411614293300167064395633287", "12750053187017853048648861493745244146555950255549630854523304068318587267293038", "53041498719137109355568081064978196049094604705283682101683207799515709404788873\ 53417136457745727045473194367732849819278740266658219147356315674940229288531", ]; #[cfg(feature = "u64_digit")] const EXPECTED_XOR: &[&str] = &[ "0", "1", "36", "970", "940965", "61158366130", "590484965100191554896", "34050066418951688801044382442803594076612", "29147581645599998811521651062569705291155276949983132826461704326818089074318948", "4990842894093964353439376569956547459232523176881032246435842690389845516810345611554402412893818283310117202233021355634125020654279500443420515862554775828", ]; #[test] fn test_xorshift_value_stability() { use rand_xorshift::XorShiftRng; seeded_value_stability::(EXPECTED_XOR); } } mod bigint { use crate::num_bigint::{BigInt, RandBigInt, RandomBits}; use num_traits::Zero; use rand::distributions::Uniform; use rand::{Rng, SeedableRng}; #[cfg(feature = "std")] fn thread_rng() -> impl Rng { rand::thread_rng() } #[cfg(not(feature = "std"))] fn thread_rng() -> impl Rng { // Chosen by fair dice roll rand::rngs::StdRng::seed_from_u64(4) } #[test] fn test_rand() { let mut rng = thread_rng(); let n: BigInt = rng.gen_bigint(137); assert!(n.bits() <= 137); assert!(rng.gen_bigint(0).is_zero()); } #[test] fn test_rand_bits() { let mut rng = thread_rng(); let n: BigInt = rng.sample(&RandomBits::new(137)); assert!(n.bits() <= 137); let z: BigInt = rng.sample(&RandomBits::new(0)); assert!(z.is_zero()); } #[test] fn test_rand_range() { let mut rng = thread_rng(); for _ in 0..10 { assert_eq!( rng.gen_bigint_range(&BigInt::from(236), &BigInt::from(237)), BigInt::from(236) ); } fn check(l: BigInt, u: BigInt) { let mut rng = thread_rng(); for _ in 0..1000 { let n: BigInt = rng.gen_bigint_range(&l, &u); assert!(n >= l); assert!(n < u); } } let l: BigInt = BigInt::from(403469000 + 2352); let u: BigInt = BigInt::from(403469000 + 3513); check(l.clone(), u.clone()); check(-l.clone(), u.clone()); check(-u.clone(), -l.clone()); } #[test] #[should_panic] fn test_zero_rand_range() { thread_rng().gen_bigint_range(&BigInt::from(54), &BigInt::from(54)); } #[test] #[should_panic] fn test_negative_rand_range() { let mut rng = thread_rng(); let l = BigInt::from(2352); let u = BigInt::from(3513); // Switching u and l should fail: let _n: BigInt = rng.gen_bigint_range(&u, &l); } #[test] fn test_rand_uniform() { let mut rng = thread_rng(); let tiny = Uniform::new(BigInt::from(236u32), BigInt::from(237u32)); for _ in 0..10 { assert_eq!(rng.sample(&tiny), BigInt::from(236u32)); } fn check(l: BigInt, u: BigInt) { let mut rng = thread_rng(); let range = Uniform::new(l.clone(), u.clone()); for _ in 0..1000 { let n: BigInt = rng.sample(&range); assert!(n >= l); assert!(n < u); } } let l: BigInt = BigInt::from(403469000 + 2352); let u: BigInt = BigInt::from(403469000 + 3513); check(l.clone(), u.clone()); check(-l.clone(), u.clone()); check(-u.clone(), -l.clone()); } fn seeded_value_stability(expected: &[&str]) { let mut seed = ::default(); for (i, x) in seed.as_mut().iter_mut().enumerate() { *x = (i as u8).wrapping_mul(191); } let mut rng = R::from_seed(seed); for (i, &s) in expected.iter().enumerate() { let n: BigInt = s.parse().unwrap(); let r = rng.gen_bigint((1 << i) + i); assert_eq!(n, r, "expected {}, got {}", n, r); } } #[cfg(not(feature = "u64_digit"))] const EXPECTED_CHACHA: &[&str] = &[ "0", "-6", "-1", "1321", "-147247", "8486373526", "-272736656290199720696", "2731152629387534140535423510744221288522", "-28820024790651190394679732038637785320661450462089347915910979466834461433196572", "501454570554170484799723603981439288209930393334472085317977614690773821680884844\ 8530978478667288338327570972869032358120588620346111979053742269317702532328", ]; #[cfg(feature = "u64_digit")] const EXPECTED_CHACHA: &[&str] = &[ "0", "-7", "-62", "105", "13025", "-33857814162", "768483926407291599143", "-42356168828789885585553598574661841382586", "28813250216034838684899917677182169473483558650956121225920149068989083656174824", "27056553770481404639717657695702187062015359344716548489861498121037858109133467\ 99640556108506718020020878739044048067894089601665199172215093468287730555599", ]; #[test] fn test_chacha_value_stability() { use rand_chacha::ChaChaRng; seeded_value_stability::(EXPECTED_CHACHA); } #[cfg(not(feature = "u64_digit"))] const EXPECTED_ISAAC: &[&str] = &[ "1", "0", "5", "113", "-132240", "-36348760761", "-365690596708430705434", "-14090753008246284277803606722552430292432", "-26313941628626248579319341019368550803676255307056857978955881718727601479436059", "-14563174552421101848999036239003801073335703811160945137332228646111920972691151\ 88341090358094331641182310792892459091016794928947242043358702692294695845817", ]; #[cfg(feature = "u64_digit")] const EXPECTED_ISAAC: &[&str] = &[ "-1", "-4", "-29", "1621", "23872", "-40371956434", "-350815272425024298187", "-38554888817044546636456097200348998322457", "7474426176220721712055446211154990065592106428397966654956172383998793852911545", "6168955541726830487961394166772329653532583907235825721475483003506842180688827\ 391385624898257369023912466314791483731902392667906094226608113824795883754631", ]; #[test] fn test_isaac_value_stability() { use rand_isaac::IsaacRng; seeded_value_stability::(EXPECTED_ISAAC); } #[cfg(not(feature = "u64_digit"))] const EXPECTED_XOR: &[&str] = &[ "-1", "-4", "11", "-1802", "966495", "-62592045703", "-602281783447192077116", "-34335811410223060575607987996861632509125", "29156580925282215857325937227200350542000244609280383263289720243118706105351199", "49920038676141573457451407325930326489996232208489690499754573826911037849083623\ 24546142615325187412887314466195222441945661833644117700809693098722026764846", ]; #[cfg(feature = "u64_digit")] const EXPECTED_XOR: &[&str] = &[ "-1", "-3", "4", "-228", "377276", "32032893086", "885120221048601050706", "33404877924318663206979407569537287223622", "-15253093455306269007559295940333933266263385975865952571271093251749752787075084", "4502641950394305250103130679458759592222756470562408577296380915684757985604969904\ 381774527626485128207406911227296090734227576935034372181808818486328078978", ]; #[test] fn test_xorshift_value_stability() { use rand_xorshift::XorShiftRng; seeded_value_stability::(EXPECTED_XOR); } } #[cfg(feature = "prime")] mod prime { use num_bigint::prime::probably_prime; use num_bigint::RandPrime; use rand::prelude::*; #[test] fn test_prime_small() { let mut rng = StdRng::from_seed([0u8; 32]); for n in 2..10 { let p = rng.gen_prime(n); assert_eq!(p.bits(), n); assert!(probably_prime(&p, 32)); } } #[test] fn test_gen_prime_1024() { let mut rng = StdRng::from_seed([0u8; 32]); let p = rng.gen_prime(1024); assert_eq!(p.bits(), 1024); } } num-bigint-dig-0.8.2/tests/roots.rs000064400000000000000000000117311046102023000153260ustar 00000000000000extern crate num_bigint_dig as num_bigint; extern crate num_integer; extern crate num_traits; #[cfg(feature = "rand")] extern crate rand; mod biguint { use crate::num_bigint::BigUint; use num_traits::{One, Pow, Zero}; use std::{i32, u32}; fn check>(x: T, n: u32) { let x: BigUint = x.into(); let root = x.nth_root(n); //println!("check {}.nth_root({}) = {}", x, n, root); if n == 2 { assert_eq!(root, x.sqrt()) } else if n == 3 { assert_eq!(root, x.cbrt()) } let lo = root.pow(n); assert!(lo <= x); assert_eq!(lo.nth_root(n), root); if !lo.is_zero() { assert_eq!((&lo - 1u32).nth_root(n), &root - 1u32); } let hi = (&root + 1u32).pow(n); assert!(hi > x); assert_eq!(hi.nth_root(n), &root + 1u32); assert_eq!((&hi - 1u32).nth_root(n), root); } #[test] fn test_sqrt() { check(99u32, 2); check(100u32, 2); check(120u32, 2); } #[test] fn test_cbrt() { check(8u32, 3); check(26u32, 3); } #[test] fn test_nth_root() { check(0u32, 1); check(10u32, 1); check(100u32, 4); } #[test] #[should_panic] fn test_nth_root_n_is_zero() { check(4u32, 0); } #[test] fn test_nth_root_big() { let x = BigUint::from(123_456_789_u32); let expected = BigUint::from(6u32); assert_eq!(x.nth_root(10), expected); check(x, 10); } #[test] fn test_nth_root_googol() { let googol = BigUint::from(10u32).pow(100u32); // perfect divisors of 100 for &n in &[2, 4, 5, 10, 20, 25, 50, 100] { let expected = BigUint::from(10u32).pow(100u32 / n); assert_eq!(googol.nth_root(n), expected); check(googol.clone(), n); } } #[test] fn test_nth_root_twos() { const EXP: u32 = 12; const LOG2: usize = 1 << EXP; let x = BigUint::one() << LOG2; // the perfect divisors are just powers of two for exp in 1..EXP + 1 { let n = 2u32.pow(exp); let expected = BigUint::one() << (LOG2 / n as usize); assert_eq!(x.nth_root(n), expected); check(x.clone(), n); } // degenerate cases should return quickly assert!(x.nth_root(x.bits() as u32).is_one()); assert!(x.nth_root(i32::MAX as u32).is_one()); assert!(x.nth_root(u32::MAX).is_one()); } #[cfg(feature = "rand")] #[test] fn test_roots_rand() { #[cfg(feature = "std")] fn thread_rng() -> impl rand::Rng { rand::thread_rng() } #[cfg(not(feature = "std"))] fn thread_rng() -> impl rand::Rng { use rand::SeedableRng; // Chosen by fair dice roll rand::rngs::StdRng::seed_from_u64(4) } use crate::num_bigint::RandBigInt; use rand::distributions::Uniform; use rand::Rng; let rng = &mut thread_rng(); let bit_range = Uniform::new(0, 2048); let sample_bits: Vec<_> = rng.sample_iter(&bit_range).take(100).collect(); for bits in sample_bits { let x = rng.gen_biguint(bits); for n in 2..11 { check(x.clone(), n); } check(x.clone(), 100); } } #[test] fn test_roots_rand1() { // A random input that found regressions let s = "575981506858479247661989091587544744717244516135539456183849\ 986593934723426343633698413178771587697273822147578889823552\ 182702908597782734558103025298880194023243541613924361007059\ 353344183590348785832467726433749431093350684849462759540710\ 026019022227591412417064179299354183441181373862905039254106\ 4781867"; let x: BigUint = s.parse().unwrap(); check(x.clone(), 2); check(x.clone(), 3); check(x.clone(), 10); check(x.clone(), 100); } } mod bigint { use crate::num_bigint::BigInt; use num_traits::{Pow, Signed}; fn check(x: i64, n: u32) { let big_x = BigInt::from(x); let res = big_x.nth_root(n); if n == 2 { assert_eq!(&res, &big_x.sqrt()) } else if n == 3 { assert_eq!(&res, &big_x.cbrt()) } if big_x.is_negative() { assert!(res.pow(n) >= big_x); assert!((res - 1u32).pow(n) < big_x); } else { assert!(res.pow(n) <= big_x); assert!((res + 1u32).pow(n) > big_x); } } #[test] fn test_nth_root() { check(-100, 3); } #[test] #[should_panic] fn test_nth_root_x_neg_n_even() { check(-100, 4); } #[test] #[should_panic] fn test_sqrt_x_neg() { check(-4, 2); } #[test] fn test_cbrt() { check(8, 3); check(-8, 3); } } num-bigint-dig-0.8.2/tests/serde.rs000064400000000000000000000050711046102023000152620ustar 00000000000000//! Test serialization and deserialization of `BigUint` and `BigInt` //! //! The serialized formats should not change, even if we change our //! internal representation, because we want to preserve forward and //! backward compatibility of serialized data! #![cfg(feature = "serde")] extern crate num_bigint_dig as num_bigint; extern crate num_traits; extern crate serde_test; use crate::num_bigint::{BigInt, BigUint}; use num_traits::{One, Zero}; use serde_test::{assert_tokens, Token}; #[test] fn biguint_zero() { let tokens = [Token::Seq { len: Some(0) }, Token::SeqEnd]; assert_tokens(&BigUint::zero(), &tokens); } #[test] fn bigint_zero() { let tokens = [ Token::Tuple { len: 2 }, Token::I8(0), Token::Seq { len: Some(0) }, Token::SeqEnd, Token::TupleEnd, ]; assert_tokens(&BigInt::zero(), &tokens); } #[test] fn biguint_one() { let tokens = [Token::Seq { len: Some(1) }, Token::U32(1), Token::SeqEnd]; assert_tokens(&BigUint::one(), &tokens); } #[test] fn bigint_one() { let tokens = [ Token::Tuple { len: 2 }, Token::I8(1), Token::Seq { len: Some(1) }, Token::U32(1), Token::SeqEnd, Token::TupleEnd, ]; assert_tokens(&BigInt::one(), &tokens); } #[test] fn bigint_negone() { let tokens = [ Token::Tuple { len: 2 }, Token::I8(-1), Token::Seq { len: Some(1) }, Token::U32(1), Token::SeqEnd, Token::TupleEnd, ]; assert_tokens(&-BigInt::one(), &tokens); } // Generated independently from python `hex(factorial(100))` const FACTORIAL_100: &'static [u32] = &[ 0x00000000, 0x00000000, 0x00000000, 0x2735c61a, 0xee8b02ea, 0xb3b72ed2, 0x9420c6ec, 0x45570cca, 0xdf103917, 0x943a321c, 0xeb21b5b2, 0x66ef9a70, 0xa40d16e9, 0x28d54bbd, 0xdc240695, 0x964ec395, 0x1b30, ]; #[test] fn biguint_factorial_100() { let n: BigUint = (1u8..101).product(); let mut tokens = vec![]; tokens.push(Token::Seq { len: Some(FACTORIAL_100.len()), }); tokens.extend(FACTORIAL_100.iter().map(|&u| Token::U32(u))); tokens.push(Token::SeqEnd); assert_tokens(&n, &tokens); } #[test] fn bigint_factorial_100() { let n: BigInt = (1i8..101).product(); let mut tokens = vec![]; tokens.push(Token::Tuple { len: 2 }); tokens.push(Token::I8(1)); tokens.push(Token::Seq { len: Some(FACTORIAL_100.len()), }); tokens.extend(FACTORIAL_100.iter().map(|&u| Token::U32(u))); tokens.push(Token::SeqEnd); tokens.push(Token::TupleEnd); assert_tokens(&n, &tokens); } num-bigint-dig-0.8.2/tests/torture.rs000064400000000000000000000021141046102023000156570ustar 00000000000000#![cfg(feature = "rand")] extern crate num_bigint_dig as num_bigint; extern crate num_traits; extern crate rand; use crate::num_bigint::RandBigInt; use num_traits::Zero; use rand::prelude::*; fn test_mul_divide_torture_count(count: usize) { let bits_max = 1 << 12; let seed = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, ]; let mut rng = rand::rngs::SmallRng::from_seed(seed); for _ in 0..count { // Test with numbers of random sizes: let xbits = rng.gen_range(0..bits_max); let ybits = rng.gen_range(0..bits_max); let x = rng.gen_biguint(xbits); let y = rng.gen_biguint(ybits); if x.is_zero() || y.is_zero() { continue; } let prod = &x * &y; assert_eq!(&prod / &x, y); assert_eq!(&prod / &y, x); } } #[test] fn test_mul_divide_torture() { test_mul_divide_torture_count(1000); } #[test] #[ignore] fn test_mul_divide_torture_long() { test_mul_divide_torture_count(1000000); }