Return Err variant of Result type

I wrote a fibonacci function and what I realized is that ouputs of inputs greater than 186 are causing overflow error as expected with u128 as return type. How can I handle the error and return it?. What I tried didn't work. Check here:

fn fibonacci(n: u8) -> Result<u128, Box<dyn std::error::Error>> {
  //where x => last term & y => current term
  if n == 0 { return Ok(0); }
  let (mut x, mut y) = (0, 1);
  for _ in 1..n {
    (x, y) = (y, x + y);
  }
  Ok(y)
}

Use checked_add (and ok_or and ?).

        let sum = x.checked_add(y).ok_or("the result is too large")?;
        (x, y) = (y, sum);

That worked alongside some changes

fn fibonacci(n: u8) -> Result<u128, Box<dyn std::error::Error>> {
  //where x => last term & y => current term
  if n == 0 { return Ok(0); }
  let mut x: u128 = 0;
  let mut y: u128 = 1;
  for _ in 1..n {
    let sum = x.checked_add(y).ok_or("the result is too large")?;
    (x, y) = (y, sum);
  }
  Ok(y)
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.