ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Custom Iterator for Fibonacci Sequence

Rust

Goal -- WPM

Ready
Exercise Algorithm Area
1struct Fibonacci {
2curr: u64,
3next: u64,
4}
5
6// Implement the Iterator trait for Fibonacci.
7impl Iterator for Fibonacci {
8type Item = u64;
9
10// The next method is called on each iteration.
11fn next(&mut self) -> Option<Self::Item> {
12// Check for potential overflow before calculating the next number.
13// If the sum of curr and next would exceed u64::MAX, we stop iteration.
14if self.curr > u64::MAX - self.next {
15return None; // Overflow detected, stop iteration
16}
17
18let new_next = self.curr + self.next;
19let current = self.curr;
20
21// Update the state for the next iteration.
22self.curr = self.next;
23self.next = new_next;
24
25// Return the current Fibonacci number.
26Some(current)
27}
28}
29
30// Helper function to create a new Fibonacci iterator.
31fn fibonacci_sequence() -> Fibonacci {
32Fibonacci { curr: 0, next: 1 }
33}
34
35fn main() {
36println!("First 10 Fibonacci numbers:");
37for (i, n) in fibonacci_sequence().take(10).enumerate() {
38println!("F({}) = {}", i, n);
39}
40
41println!("\nFibonacci numbers until overflow (approximate):");
42// Iterate until overflow is detected by the iterator.
43for n in fibonacci_sequence() {
44println!("{}", n);
45}
46
47// Example of using take_while to stop at a certain value.
48println!("\nFibonacci numbers less than 100:");
49for n in fibonacci_sequence().take_while(|&x| x < 100) {
50println!("{}", n);
51}
52}
Algorithm description viewbox

Custom Iterator for Fibonacci Sequence

Algorithm description:

This Rust code implements a custom iterator for generating the Fibonacci sequence. The `Fibonacci` struct maintains the state of the sequence (current and next numbers). The `Iterator` trait is implemented, with the `next` method calculating the subsequent Fibonacci number and handling potential `u64` overflow. This allows for efficient, on-demand generation of Fibonacci numbers without pre-calculating a large list.

Algorithm explanation:

The `Fibonacci` struct holds two `u64` values: `curr` and `next`, representing the current and the next number in the sequence, respectively. The `Iterator` trait's `next` method is implemented to return the `curr` value and then update `curr` to `next` and `next` to their sum. A crucial aspect is the overflow check: `if self.curr > u64::MAX - self.next`. If adding `self.curr` and `self.next` would exceed `u64::MAX`, `None` is returned, signaling the end of iteration. The time complexity for generating each Fibonacci number is O(1). The space complexity is O(1) as it only stores two numbers. This approach is efficient and handles the sequence generation until the limits of `u64` are reached.

Pseudocode:

struct Fibonacci:
  current_number: unsigned 64-bit integer
  next_number: unsigned 64-bit integer

implement Iterator for Fibonacci:
  type Item = unsigned 64-bit integer

  method next(&mut self) -> Option<Item>:
    if current_number > MAX_U64 - next_number:
      return None (overflow)

    let temp_current = current_number
    current_number = next_number
    next_number = temp_current + next_number

    return Some(temp_current)

function fibonacci_sequence() -> Fibonacci:
  return new Fibonacci with current_number = 0, next_number = 1