How do I generate a random num::BigUint?

2019-08-14 20:29发布

问题:

I need a random 256-bit unsigned number. I discovered that there is the RandBigInt trait with the method gen_biguint(), but I am having a tough time finding an implementation for it.

I tried doing this some time ago for BigInt. The crates have been updated since. This is how I am using it to get a BigUint now.

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;
            }
            _ => {}
        }
    }
}

Contents from my Cargo.toml

num = "0.1.42"
rand = "0.4.2"

I am sure there must be some straight-forward way of achieving this.

回答1:

From the README of num:

The rand feature enables randomization traits in num-bigint and num-complex.

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

Then you need to use a RandomBits which implements 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)
}


回答2:

Shepmaster's answer was raising a trait bound error in more recent versions of rand. Got this to work:

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);  
}


标签: rust bigint