Large sum returns negative numbers in julia

hello ,
i am trying to do a counter for some problem I am having, but while I was testing I see that Julia was returning negative numbers after some time,
I have no idea why this is happening,

now to check that, i have added print with condition that 'weird limit has hit,
is this a bug ,

adding the counter code
‘’‘function counter(x)
y = 0
for i in 0:x
y=y+x
if y<0
print(i)
return “weird limit hit”
#rint(i)
end
end
print(y)
end
‘’’
execution @time counter(10000000000)
outputs of weird limits
922337203 0.000041 seconds (17 allocations: 368 bytes)
weird limit hit"

execution @time counter(10000000000000)
922337 0.000040 seconds (17 allocations: 368 bytes)

Out[16]:

“weird limit hit”

This is integer overflow. Once the maximum integer number is hit, it will jump to the smallest:

julia> typemax(Int)
9223372036854775807

julia> typemax(Int)+1
-9223372036854775808

You can avoid this by using floats or BigInt.

There have been quite a few posts on this on this forum, search them for more details.

PS: please quote your code, see Please read: make it easier to help you

6 Likes

Also see
https://docs.julialang.org/en/v1/manual/faq/#faq-integer-arithmetic

8 Likes

thanks for the info , i will try with bigint and thanks for teh psa one as well

1 Like

Before going to BigInt you could try Int128, which are much faster, and see if they are enough.

5 Likes

thanks for teh advise nd thanks for this this had really solved my problem