我想使用 Rust 创建斐波那契数列列表 我写了这段代码,但我认为有更干净和简短的方法来做到这一点 ...................................................... ................................................
fn main() {
let mut first_num: i128 = 0;
let mut second_num:i128 = 1;
let mut resulte: i128;
let mut list = Vec::with_capacity(200);
while list.len() < 100 {
resulte = first_num + second_num;
list.push(resulte);
println!("The Fib Number is: {}", resulte);
second_num = first_num;
first_num = resulte;
}
}
非递归函数。
n
用于计算序列成员的排名。
pub fn fibonacci(n: i32) -> u64 {
if n < 0 {
panic!("{} is negative!", n);
} else if n == 0 {
panic!("zero is not a right argument to fibonacci()!");
} else if n == 1 {
return 1;
}
let mut sum = 0;
let mut last = 0;
let mut curr = 1;
for _i in 1..n {
sum = last + curr;
last = curr;
curr = sum;
}
sum
}
递归函数。
这段代码展示了计算斐波那契数列的递归方法,复杂度是指数级的。
n
用于计算序列成员的排名。
pub fn fibonacci_reccursive(n: i32) -> u64 {
if n < 0 {
panic!("{} is negative!", n);
}
match n {
0 => panic!("zero is not a right argument to fibonacci_reccursive()!"),
1 | 2 => 1,
3 => 2,
/*
50 => 12586269025,
*/
_ => fibonacci_reccursive(n - 1) + fibonacci_reccursive(n - 2),
}
}