2个不稳定版本
使用旧的Rust 2015
0.2.0 | 2018年6月26日 |
---|---|
0.1.0 | 2018年6月19日 |
1330 在 数据结构 中
40KB
723 行
largeint
支持大整数算术的库。
入门指南
首先,将 largeint 添加到你的依赖项中
[dependencies]
largeint = "0.2.0"
接下来,将以下内容添加到你的 crate 根目录,以便将 largeint 的内容纳入你的项目范围
extern crate largeint;
use largeint::largeint::*;
然后,你可以轻松地创建许多 LargeInt
实例
let largeint1 = new(String::from("999999999999999999999"), Sign::Positive);
let largeint2 = new(String::from("999999999999999999999"), Sign::Negative);
let largeint3 = new(String::from("0"), Sign::Unsigned);
LargeInt
实例包含两个字段,整数存储的标量值作为 String
,整数存储的符号作为枚举 Sign
,可以是 Positive
,Negative
或 Unsigned
(请注意,0
是唯一应该分配 Unsigned
的整数)。
强烈推荐使用 new
来创建 LargeInt
实例,因为其中包含检查以确保 LargeInt
实例能够正确创建。例如,使用 new
创建标量值为 0
的 LargeInt
实例将自动将 Sign::Unsigned
分配给 LargeInt 的符号,即使你输入了另一个 Sign
变体。
该库的目的是提供 Rust 中易于使用的整数实现。理想的用户是那些想要编写个人小型项目并且不希望花大量时间学习像 num-bigint 这样复杂 crate 的人。例如,这个库非常适合解决 Project Euler 问题 13。然而,largeint 库并不特别高效,因此建议对于更严肃的项目使用 num-bigint 这样的 crate。
让我们看看进行大整数运算有多简单!
示例
extern crate largeint;
use largeint::largeint::*;
fn main() {
// Adding two LargeInts.
let largeint1 = new(String::from("33901489213409093401849249010492000112"), Sign::Positive);
let largeint2 = new(String::from("8294839402902010934029489031849310009324234230"), Sign::Negative);
let largeint3 = largeint1.add(&largeint2);
let largeint4 = new(String::from("8294839369000521720620395630000060998832234118"), Sign::Negative);
assert_eq!(largeint3,largeint4);
// Subtracting two LargeInts.
let largeint1 = new(String::from("33901489213409093401849249010492000112"), Sign::Negative);
let largeint2 = new(String::from("100320394280329423048093284093240234809833999"), Sign::Negative);
let largeint3 = largeint1.sub(&largeint2);
let largeint4 = new(String::from("100320360378840209638999882243991224317833887"), Sign::Positive);
assert_eq!(largeint3,largeint4);
// Multiplying two LargeInts.
let largeint1 = new(String::from("239014892134090934018492404920112"), Sign::Negative);
let largeint2 = new(String::from("820948948039443908494308943885"), Sign::Negative);
let largeint3 = largeint1.mul(&largeint2);
let largeint4 = new(String::from("196219024263243108752932957733805138559777844813650340515915120"), Sign::Positive);
assert_eq!(largeint3,largeint4);
// Dividing two LargeInts.
let largeint1 = new(String::from("33901489213409093401849249010492088384894374938712"), Sign::Positive);
let largeint2 = new(String::from("1003203942803294230480932840934343489333999"), Sign::Negative);
let largeint3 = largeint1.div(&largeint2);
let largeint4 = new(String::from("33793217"), Sign::Negative);
assert_eq!(largeint3,largeint4);
//The get_int() method returns the scalar value of the LargeInt as a String.
println!("The value of largeint1 is: {}", largeint1.get_int());
//The get_sign() method returns the Sign of the LargeInt as a String.
println!("The Sign of largeint1 is: {}", largeint1.get_sign());
}
更新
代码破坏性更改:减法方法已从 subtraction
重命名为 sub
。
新库添加:乘法、整数除法 - 及余数 - 已添加。
许可证
本项目采用 MIT 许可证 - 有关详细信息,请参阅 LICENSE.md。