斐波那契数列指的是这样一个数列 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368……..
这个数列从第3项开始,每一项都等于前两项之和
。
f(x) = f(x-1) + f(x-2)
实现计算的Rust代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| fn main(){ for i in 1..101 { println!("f({})=f({}-1)+f({}-2) = {}", i , i, i, ran(i)); } }
fn ran(mut i: i32) -> i128 { let mut total: i128 = 0; let mut t_1: i128 = 1; let mut t_2: i128 = 1; while i > 2 { total = t_1 + t_2; t_1 = t_2; t_2 = total; i -= 1; } return total; }
|
运行结果
1 2 3 4 5 6 7 8 9 10 11 12
| f(1)=f(1-1)+f(1-2) = 0 f(2)=f(2-1)+f(2-2) = 0 f(3)=f(3-1)+f(3-2) = 2 f(4)=f(4-1)+f(4-2) = 3 f(5)=f(5-1)+f(5-2) = 5 f(6)=f(6-1)+f(6-2) = 8 f(7)=f(7-1)+f(7-2) = 13 f(8)=f(8-1)+f(8-2) = 21 f(9)=f(9-1)+f(9-2) = 34 f(10)=f(10-1)+f(10-2) = 55 ... f(100)=f(100-1)+f(100-2) = 354224848179261915075
|