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