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)
}
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)
}