Home > Blockchain >  thread 'main' panicked at 'attempt to add with overflow', test.rs:15:12
thread 'main' panicked at 'attempt to add with overflow', test.rs:15:12

Time:02-10

I have been learning rust while practicing recursion. So this is just a simple recursive problem and the type is an signed8 and should be working. But I get this error which I am not able to understand why.

The base case is correct and the calls recursive calls are correct as well.

fn main() {
    let num = ways_to_climb(10);
    println!("{}", num);
}

fn ways_to_climb(n: i8) -> i8 {

    println!("{}", n);
    if n == 0 || n == 1 {
        return 1;
    }
    if n < 0 {
        return 0;
    }
    return ways_to_climb(n - 1)   ways_to_climb(n - 2)   ways_to_climb(n - 3);
}

CodePudding user response:

Let's add some more logging:

fn main() {
    let num = ways_to_climb(10);
    println!("{}", num);
}

fn ways_to_climb(n: i8) -> i8 {
    if n == 0 || n == 1 {
        return 1;
    }
    if n < 0 {
        return 0;
    }
    
    let (a, b, c) = (ways_to_climb(n - 1), ways_to_climb(n - 2), ways_to_climb(n - 3));
    println!("{}   {}   {}", a, b, c);
    return a   b   c;
}

As we can see, the operation it panics on is:

81   44   24

Indeed, that's 149, and an i8 can only hold -128 to 127. 149 is > 127, so we overflowed.

You'll need a bigger type than i8 to calculate ways_to_climb(10).

CodePudding user response:

The overflow is because of i8. Use i32 instead, which is usually default.

fn main() {
    let num = ways_to_climb(10);
    println!("{}", num);
}

fn ways_to_climb(n: i32) -> i32 {
    
   println!("{}", n);
   if n == 0 || n == 1 {
    return 1;
   }
   if n < 0 {
    return 0;
   }
   return ways_to_climb(n - 1)   ways_to_climb(n - 2)   ways_to_climb(n - 3);
}
  • Related