How do I generate a random num::BigUint?

纵饮孤独 提交于 2019-12-11 06:17:47

问题


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


来源:https://stackoverflow.com/questions/51640381/how-do-i-generate-a-random-numbiguint

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!