implement fibonacci sequence in rust
- User
implement fibonacci sequence in rust
Assistant
Here's a Rust implementation of the Fibonacci sequence with several different approaches:
// Recursive approach (simple but inefficient for large numbers) fn fibonacci_recursive(n: u32) -> u64 { match n { 0 => 0, 1 => 1, _ => fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2), } } // Iterative approach (efficient) fn fibonacci_iterative(n: u32) -> u64 { if n <= 1 { return n as u64; } let mut prev = 0u64; let mut curr = 1u64; for _ in 2..=n { let next = prev + curr; prev = curr; curr = next; } curr } // Iterator-based approach fn fibonacci_sequence(count: usize) -> Vec<u64> { let mut sequence = Vec::with_capacity(count); let mut a = 0u64; let mut b = 1u64; for _ in 0..count { sequence.push(a); let next = a + b; a = b; b = next; } sequence } // Custom iterator implementation struct FibonacciIterator { current: u64, next: u64, } impl FibonacciIterator { fn new() -> Self { FibonacciIterator { current: 0, next: 1, } } } impl Iterator for FibonacciIterator { type Item = u64; fn next(&mut self) -> Option<Self::Item> { let current = self.current; self.current = self.next; self.next = current + self.next; Some(current) } } fn main() { // Test the recursive approach println!("Recursive fibonacci(10): {}", fibonacci_recursive(10)); // Test the iterative approach println!("Iterative fibonacci(10): {}", fibonacci_iterative(10)); // Generate first 10 fibonacci numbers let sequence = fibonacci_sequence(10); println!("First 10 fibonacci numbers: {:?}", sequence); // Using the custom iterator let fib_iter = FibonacciIterator::new(); let first_10: Vec<u64> = fib_iter.take(10).collect(); println!("Using iterator: {:?}", first_10); // Generate fibonacci numbers up to a limit let fib_under_100: Vec<u64> = FibonacciIterator::new() .take_while(|&x| x < 100) .collect(); println!("Fibonacci numbers under 100: {:?}", fib_under_100); }The iterative approach is generally preferred for performance since it runs in O(n) time and O(1) space, while the recursive approach has exponential time complexity. The iterator implementation is particularly idiomatic in Rust and allows for flexible usage patterns like generating sequences up to certain limits or taking specific numbers of elements.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.