What is the error "thread 'main' panicked at 'attempt to subtract with overflow"?

What is the error "thread 'main' panicked at 'attempt to subtract with overflow"?

use std::io;
fn read<T: std::str::FromStr>() -> Vec<T> {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    buf.trim().split(' ').flat_map(str::parse).collect()
fn solve(i:usize, m:usize, a:&Vec<usize>) -> bool{
    if m == 0{
        return true;
    if i >= m{
        return false;
    return solve(i + 1, m, a) || solve(i + 1, m - a[i], a);
fn main() {
    let _n = read::<usize>();
    let a = read::<usize>();
    let q = read::<usize>();
    let m = read::<usize>();
    for i in 0..q[0]{
        if solve(0, m[i],&a) == true{

1 5 7 10 21
2 4 17 8

It means exactly what it says. One of the subtraction operations resulted in a value that over- or underflowed. For example, int32::MIN - 1 can cause such a panic in debug mode. The only subtraction I see in your code is m - a[i], so you will need to check what this does and fix the error there.

A value x: usize can only hold integer values from 0 to 2^64 - 1, including the ends (on 64-bit CPU architectures, which you use now). If the result of an arithmetic operation cannot fit in this range, you get an overflow error in debug mode or an arithmetic wrapping in release mode. Wrapping means that the result is the same as if you did the operation on infinite precision integers, and then take the remainder of division by 2^64, producing the value in the range above.

So 0_usize - 1 will either panic in dev build with overflow error, or wrap around and produce 2^64 - 1 in release mode (more generally, whenever overflow checks are disabled). Most of the time wrapping is a major bug which can cause all kinds of problems, but overflow checks can inhibit optimizations. For this reason the checks are, by default, performed only in dev builds. You can manually enable or disable overflow checks in any build using the overflow-checks Cargo profile option. You can also explicitly perform wrapping arithmetics, if you need to, using the wrapping_add, wrapping_sub etc family of operations.

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.