Looping with a for is resulting a negative number

Hi everyone!

I´m facing a problem while doing one exercise. I have the next piece of code and the desired result is to give me all these numbers as absolute values (not negatives), but in the last element of the loop for (i=64) is resulting me in a negative one. I am doing something wrong or misunderstanding the loop behaviour?

Thank you very much!

declare -i sheet=1

for i in {2..64}
do
        echo "$sheet" "before"
        echo "$((sheet*2))" "after"
        sheet=$((sheet*2))
done

I suspect you’re running into this:

$ for i in 61 62 63 64; do
    echo $i $((2**i - 1)) $((2**i))
done
61 2305843009213693951 2305843009213693952
62 4611686018427387903 4611686018427387904
63 9223372036854775807 -9223372036854775808
64 -1 0

That’s because bash integers are signed, so the largest positive int is 2^63 - 1

There’s a trick though: use printf to print a long-unsigned int

$ for i in 61 62 63 64; do
    printf "%d %lu %lu\n" $i $((2**i - 1)) $((2**i))
done
61 2305843009213693951 2305843009213693952
62 4611686018427387903 4611686018427387904
63 9223372036854775807 9223372036854775808
64 18446744073709551615 0
1 Like

Ooh I didn´t know about that integer limitation. Thank you very much!!! it was a really annoying issue :sweat_smile:

Note, integer overflow is a pretty common problem across many languages.

1 Like