使用以下功能时:
fn factors(number: &BigInt) -> Vec<BigInt> {
let mut n = number.clone();
let mut i: BigInt = ToBigInt::to_bigint(&2).unwrap();
let mut factors = Vec::<BigInt>::new();
while i * i <= n {
if (n % i) == ToBigInt::to_bigint(&1).unwrap() {
i = i + ToBigInt::to_bigint(&1).unwrap();
}
else {
n = n/i as BigInt;
factors.push(i);
}
i = i + ToBigInt::to_bigint(&1).unwrap();
}
if n > i {
factors.push(n);
}
factors
}
Run Code Online (Sandbox Code Playgroud)
我每次都会得到移动的值错误i
或者n
被使用,从行开始while
,也在if
.我读过关于借用的内容,我理解得很清楚,但这件事我不明白.我根本没有"复制"这个值,所以我没有看到任何地方我可能失去变量的所有权.
Mul
(以及其他算术运算符)按值获取参数,因此i * i
移动该值i
(这对于原始数字不是问题,因为它们实现Copy
- BigInt
不是).
正如Mul
(两个)实现的那样&BigInt
,你可以用以下函数进行乘法(和其他算术运算)&
:
use num::*;
fn factors(number: &BigInt) -> Vec<BigInt> {
let mut n = number.clone();
let mut i = BigInt::from(2);
let mut factors = Vec::new();
while &i * &i <= n {
if (&n % &i) == BigInt::one() {
i = i + BigInt::one();
} else {
n = n / &i;
factors.push(i.clone());
}
i = i + BigInt::one();
}
if n > i {
factors.push(n);
}
factors
}
Run Code Online (Sandbox Code Playgroud)
请注意,我也做了一些简化,比如省略类型Vec::new
和使用BigInt::from
(不能失败).
归档时间: |
|
查看次数: |
2152 次 |
最近记录: |