简体   繁体   English

如何生成随机num :: BigUint?

[英]How do I generate a random num::BigUint?

I need a random 256-bit unsigned number. 我需要一个随机的256位无符号数字。 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. 我发现使用gen_biguint()方法具有RandBigInt特性,但是我很难为它找到实现。

I tried doing this some time ago for BigInt . 我曾在BigInt尝试过这样做。 The crates have been updated since. 此后,箱子已更新。 This is how I am using it to get a BigUint now. 这就是我现在用它来获取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;
            }
            _ => {}
        }
    }
}

Contents from my Cargo.toml 我的Cargo.toml中的内容

num = "0.1.42"
rand = "0.4.2"

I am sure there must be some straight-forward way of achieving this. 我确信必须有一些简单的方法来实现这一目标。

From the README of num : num的自述文件:

The rand feature enables randomization traits in num-bigint and num-complex . rand功能启用num-bigintnum-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 : 然后,您需要使用实现rand::DistributionRandomBits

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

Shepmaster's answer was raising a trait bound error in more recent versions of rand. Shepmaster的答案是在较新版本的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);  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM