little example

This commit is contained in:
NikVolf 2017-05-21 12:56:25 +03:00
parent c86bbaaee7
commit 91d4e57588
2 changed files with 57 additions and 2 deletions

56
examples/modular.rs Normal file
View File

@ -0,0 +1,56 @@
// Copyright 2015-2017 Parity Technologies
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate bigint;
use bigint::U256;
fn main() {
// Example modular arithmetic using bigint U256 primitives
// imagine the field 0..p
// where the p is defined below
// (it's a prime!)
let p = U256::from_dec_str(
"38873241744847760218045702002058062581688990428170398542849190507947196700873"
).expect("Generator to be a parsable number");
// then, on this field,
// (p-1) + (p+1) = 0
// (p - 1) mod p
let (p_minus_1, _) = (p - 1u64.into()).overflowing_rem(p);
// (p + 1) mod p
let (p_plus_1, _) = (p + 1u64.into()).overflowing_rem(p);
// ((p - 1) mod p + (p + 1) mod p) mod p
let (sum, _) = (p_minus_1 + p_plus_1).overflowing_rem(p);
assert_eq!(sum, 0.into());
// on this field,
// (p-1) + (p-1) = p-2
let (p_minus_1, _) = (p - 1u64.into()).overflowing_rem(p);
let (sum, _) = (p_minus_1 + p_minus_1).overflowing_rem(p);
assert_eq!(sum, p - 2.into());
// on this field,
// (p-1) * 3 = p-3
let (p_minus_1, _) = (p - 1u64.into()).overflowing_rem(p);
// multiplication is a series of additions
let multiplicator = 3;
let mul = {
let mut result = p_minus_1;
for _ in 0..multiplicator-1 {
let (s, _) = (p_minus_1 + result).overflowing_rem(p);
result = s;
}
result
};
assert_eq!(mul, p - 3.into());
}

View File

@ -6,7 +6,6 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Code derived from original work by Andrew Poelstra <apoelstra@wpsoftware.net>
// Rust Bitcoin Library
@ -1883,7 +1882,7 @@ mod tests {
let (result, overflow) =
U256([::std::u64::MAX, ::std::u64::MAX, ::std::u64::MAX, ::std::u64::MAX])
.overflowing_sub(U256([::std::u64::MAX/2, ::std::u64::MAX/2, ::std::u64::MAX/2, ::std::u64::MAX/2]));
assert!(!overflow);
assert_eq!(U256([::std::u64::MAX/2+1, ::std::u64::MAX/2+1, ::std::u64::MAX/2+1, ::std::u64::MAX/2+1]), result);