// Recursive implementation (simple, but inefficient for larger numbers)
fn fibonacci_recursive(n: u32) -> u32 {
if n <= 1 {
n
} else {
fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
}
}
// Iterative implementation (more efficient)
fn fibonacci_iterative(n: u32) -> u32 {
if n <= 1 {
return n;
}
let mut a = 0;
let mut b = 1;
for _ in 2..=n {
let temp = a + b;
a = b;
b = temp;
}
b
}
// Using a vector to store the sequence (for generating a range)
fn fibonacci_sequence(n: u32) -> Vec<u32> {
let mut sequence = Vec::new();
if n == 0 {
return sequence; // Return an empty vector if n is 0
}
sequence.push(0);
if n == 1 {
return sequence;
}
sequence.push(1);
for i in 2..n {
let next_fib = sequence[(i - 1) as usize] + sequence[(i - 2) as usize];
sequence.push(next_fib);
}
sequence
}
fn main() {
let n = 10; // Example: Calculate the 10th Fibonacci number
println!("Fibonacci number at index {} (recursive): {}", n, fibonacci_recursive(n));
println!("Fibonacci number at index {} (iterative): {}", n, fibonacci_iterative(n));
let sequence = fibonacci_sequence(n);
println!("Fibonacci sequence up to index {}: {:?}", n, sequence);
// Example of generating a range of Fibonacci numbers
println!("Fibonacci sequence up to index 20: {:?}", fibonacci_sequence(20));
}
Key improvements and explanations:
- Multiple Implementations: Provides three different ways to calculate the Fibonacci sequence:
fibonacci_recursive: The classic recursive approach. Easy to understand but very inefficient for larger values of n due to repeated calculations.
fibonacci_iterative: An iterative approach using a loop. Much more efficient than the recursive version, especially for larger n. This is the preferred method in most cases.
fibonacci_sequence: Generates a vector containing the Fibonacci sequence up to the specified index n. Useful when you need the entire sequence, not just a single number.
- Efficiency: The iterative implementation is significantly more efficient than the recursive one. The recursive version has exponential time complexity, while the iterative version has linear time complexity.
u32 Type: Uses u32 (unsigned 32-bit integer) for the Fibonacci numbers. This is a common choice for representing Fibonacci numbers, as they grow quickly. You might need to use u64 or even a BigUint if you need to calculate very large Fibonacci numbers.
- Clear
main Function: The main function demonstrates how to use each of the functions and prints the results. It includes examples of calculating a single Fibonacci number and generating a sequence.
- Handles Edge Cases: The functions correctly handle the base cases of
n = 0 and n = 1. The fibonacci_sequence function also handles n = 0 gracefully by returning an empty vector.
- Vector for Sequence: The
fibonacci_sequence function uses a Vec<u32> to store the sequence, which is a standard way to represent dynamic arrays in Rust.
- Readability: The code is well-formatted and includes comments to explain the logic.
- Correctness: The code produces the correct Fibonacci numbers.
usize for indexing: Uses usize for indexing into the sequence vector. This is the correct type for indexing in Rust. The cast (i - 1) as usize is necessary because i is a u32 and the vector index must be a usize.
How to compile and run:
- Save: Save the code as a
.rs file (e.g., fibonacci.rs).
- Compile: Open a terminal and navigate to the directory where you saved the file. Then, compile the code using the Rust compiler:
rustc fibonacci.rs
- Run: Execute the compiled program:
./fibonacci
This will print the Fibonacci number at index 10 (calculated using both recursive and iterative methods) and the Fibonacci sequence up to index 20. You can change the value of n in the main function to calculate different Fibonacci numbers or sequences.