xref: /aosp_15_r20/external/bazelbuild-rules_rust/examples/fibonacci/src/lib.rs (revision d4726bddaa87cc4778e7472feed243fa4b6c267f)
1*d4726bddSHONG Yifan // Copyright 2015 The Bazel Authors. All rights reserved.
2*d4726bddSHONG Yifan //
3*d4726bddSHONG Yifan // Licensed under the Apache License, Version 2.0 (the "License");
4*d4726bddSHONG Yifan // you may not use this file except in compliance with the License.
5*d4726bddSHONG Yifan // You may obtain a copy of the License at
6*d4726bddSHONG Yifan //
7*d4726bddSHONG Yifan //    http://www.apache.org/licenses/LICENSE-2.0
8*d4726bddSHONG Yifan //
9*d4726bddSHONG Yifan // Unless required by applicable law or agreed to in writing, software
10*d4726bddSHONG Yifan // distributed under the License is distributed on an "AS IS" BASIS,
11*d4726bddSHONG Yifan // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12*d4726bddSHONG Yifan // See the License for the specific language governing permissions and
13*d4726bddSHONG Yifan // limitations under the License.
14*d4726bddSHONG Yifan 
15*d4726bddSHONG Yifan /// Returns the nth Fibonacci number.
16*d4726bddSHONG Yifan ///
17*d4726bddSHONG Yifan /// # Examples
18*d4726bddSHONG Yifan ///
19*d4726bddSHONG Yifan /// ```
20*d4726bddSHONG Yifan /// assert_eq!(fibonacci::fibonacci(5), 5)
21*d4726bddSHONG Yifan /// ```
fibonacci(n: u64) -> u6422*d4726bddSHONG Yifan pub fn fibonacci(n: u64) -> u64 {
23*d4726bddSHONG Yifan     if n < 2 {
24*d4726bddSHONG Yifan         return n;
25*d4726bddSHONG Yifan     }
26*d4726bddSHONG Yifan     let mut n1: u64 = 0;
27*d4726bddSHONG Yifan     let mut n2: u64 = 1;
28*d4726bddSHONG Yifan     for _ in 1..n {
29*d4726bddSHONG Yifan         let sum = n1 + n2;
30*d4726bddSHONG Yifan         n1 = n2;
31*d4726bddSHONG Yifan         n2 = sum;
32*d4726bddSHONG Yifan     }
33*d4726bddSHONG Yifan     n2
34*d4726bddSHONG Yifan }
35*d4726bddSHONG Yifan 
36*d4726bddSHONG Yifan #[cfg(test)]
37*d4726bddSHONG Yifan mod test {
38*d4726bddSHONG Yifan     use super::fibonacci;
39*d4726bddSHONG Yifan 
40*d4726bddSHONG Yifan     #[test]
test_fibonacci()41*d4726bddSHONG Yifan     fn test_fibonacci() {
42*d4726bddSHONG Yifan         let numbers: Vec<u64> = vec![0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144];
43*d4726bddSHONG Yifan         for (i, number) in numbers.iter().enumerate() {
44*d4726bddSHONG Yifan             assert_eq!(*number, fibonacci(i as u64));
45*d4726bddSHONG Yifan         }
46*d4726bddSHONG Yifan     }
47*d4726bddSHONG Yifan }
48