0

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

nassqra
  • 351
  • 1
  • 3
  • 14
  • Are you sure the output of `ways_to_climb` will always fit into an 8-bit (!) signed integer `i8`? – ForceBru Feb 09 '22 at 16:00
  • Does this answer your question? [What happens in Rust programming language when an integer arithmetic operation overflows?](https://stackoverflow.com/questions/68807024/what-happens-in-rust-programming-language-when-an-integer-arithmetic-operation-o) – E_net4 Feb 09 '22 at 16:09

2 Answers2

2

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

canton7
  • 37,633
  • 3
  • 64
  • 77
1

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);
}
E_net4
  • 27,810
  • 13
  • 101
  • 139
nassqra
  • 351
  • 1
  • 3
  • 14