当前位置:网站首页>[rust weekly database] num bigint - large integer

[rust weekly database] num bigint - large integer

2022-06-30 10:42:00 51CTO

We know rust The maximum number of integers supported in standard types is U128, So if you want to use an integer larger than this size ( It's mostly programming / Scientific operation / Blockchain ) What to do ? This is when we need our ​​num-bigint​​​ The library . Note that this library is included in ​​num​​​ This is in the yuan bank . We will introduce... For convenience ​​num​​ library .

[dependencies]
num = "0.3"

If you want to use it alone ​​num-bigint​​ Then you can.

[dependencies]
num-bigint = "0.3"

Basic usage

Let's take the calculation of Fibonacci sequence as an example :

use num::bigint::BigUint;
use num::traits::{Zero, One};
use std::mem::replace;

// The logic of calculating Fibonacci sequence
fn fib(n: usize) -> BigUint {
letmut f0: BigUint = Zero::zero();
letmut f1: BigUint = One::one();
for _ in0..n {
let f2 = f0 + &f1; // Be careful &
// f0 <- f1, f1 <- f2
f0 = replace(&mut f1, f2);
}
f0
}

fn main() {
println!("fib(1000) = {}", fib(1000));
}

Random large numbers

Can also cooperate ​​rand​​​ Generating random large numbers . You need to use ​​rand​​​ Of feature, also ​​rand​​ At present, you can only use 0.7 edition

[dependencies]
rand = "0.7"
num = { version = "0.3", features = ["rand"] }

Then you can generate random numbers

use num::bigint::{ToBigInt, RandBigInt};

fn main() {

// Randomly generate one bigint
letmut rng = rand::thread_rng();
let a = rng.gen_bigint(1000);

// Generate a specific range of bigint
let low = -10000.to_bigint().unwrap();
let high = 10000.to_bigint().unwrap();
let b = rng.gen_bigint_range(&low, &high);

println!("{}", a * b);
}

That's all ​​num-bigint​​​ The basic usage of .​​num​​ There are some other practical contents in the library that you can also explore .


原网站

版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/181/202206300937189699.html