Fibonacci Sequence
Level: medium (score: 3)
💡 Individual exercises are great, but nothing beats building a real-world app with Rust.
Check out our Rust Intro Cohort Program!
Implement the fibonacci
function that takes an integer n
as input and returns the n
th Fibonacci number.
The Fibonacci sequence is a series of numbers where each number (after the first two) is the sum of the two preceding ones. The sequence starts with 0 and 1. For example, the sequence begins: 0, 1, 1, 2, 3, 5, 8, ...
If the input is a negative number, the function should handle it by panicking with a meaningful error message.
-
Given a valid input
n = 5
, the function should return5
:let result = fibonacci(5); // 5
-
Given another valid input
n = 10
, the function should return55
:let result = fibonacci(10); // 55
-
If the input is a negative number, such as
n = -1
, the function should panic with an error message:fibonacci(-1); // Should panic with "Negative input is not allowed"
fn fibonacci(n: i32) -> u32 {
// Hint: Use a `match` expression to handle different cases:
// - For n < 0, you can panic or handle the error gracefully.
// - For n = 0, the result is 0.
// - For n = 1, the result is 1.
// - For other values of n, recursively calculate the
// sum of the two preceding numbers.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_fibonacci() {
assert_eq!(fibonacci(0), 0);
assert_eq!(fibonacci(1), 1);
assert_eq!(fibonacci(5), 5);
assert_eq!(fibonacci(10), 55);
assert_eq!(fibonacci(20), 6765);
}
#[test]
#[should_panic]
fn test_fibonacci_negative() {
fibonacci(-1); // Should panic for negative input
}
}