我需要一个随机的256位无符号数字。我发现方法gen_biguint()
具有RandBigInt
特性,但是我很难为它找到实现。
前段时间,我尝试为BigInt
执行此操作。此后,箱子已更新。这就是我现在使用它来获取BigUint
的方式。
extern crate num;
extern crate rand;
use num::bigint::{BigInt, BigUint, RandBigInt};
fn main() {
let mut rng = rand::thread_rng();
let mut n: BigUint = BigUint::default();
loop {
let bigUint: Option<BigUint> = rng.gen_bigint(256).to_biguint();
match bigUint {
Some(num) => {
n = num.clone();
println!("Found the 1st BigUint - {}", num);
break;
}
_ => {}
}
}
}
我的 Cargo.toml
中的内容num = "0.1.42"
rand = "0.4.2"
我确信必须有一些简单的方法来实现这一目标。
答案 0 :(得分:5)
摘自num
的自述文件:
rand
功能可在num-bigint
和num-complex
中启用随机特征。
[dependencies]
num-bigint = { version = "0.2.0", features = ["rand"] }
rand = "0.5.4"
然后,您需要使用实现RandomBits
的rand::Distribution
:
extern crate num_bigint;
extern crate rand;
use num_bigint::{BigInt, BigUint, RandomBits};
use rand::Rng;
fn main() {
let mut rng = rand::thread_rng();
let signed: BigInt = rng.sample(RandomBits::new(256));
let unsigned: BigUint = rng.sample(RandomBits::new(256));
println!("{}, {}", signed, unsigned)
}
答案 1 :(得分:0)
Shepmaster的答案是在较新版本的rand中引发特征绑定错误。使它起作用:
Cargo.toml
edition = "2018"
[dependencies]
rand = "0.6"
num-bigint = { version = "0.2.2", features = ["rand"] }
main.rs
use num_bigint::{BigUint, RandBigInt};
fn main() {
let mut rng = rand::thread_rng();
let unsigned: BigUint = rng.gen_biguint(256);
println!("{}", unsigned);
}