如何生成随机的num :: BigUint?

时间:2018-08-01 18:49:21

标签: rust bigint

我需要一个随机的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"

我确信必须有一些简单的方法来实现这一目标。

2 个答案:

答案 0 :(得分:5)

摘自num的自述文件:

  

rand功能可在num-bigintnum-complex中启用随机特征。

[dependencies]
num-bigint = { version = "0.2.0", features = ["rand"] }
rand = "0.5.4"

然后,您需要使用实现RandomBitsrand::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);  
}