Skip to content
Advertisement

Integer overflow while calculating all possible sums of n*m matrix rows

I am using this code to compute all possible sum of a n x m matrix. The code is working absolutely fine and it is fast too when using arrays of 32-bit integers like [[777,675,888],[768,777,698]]. It is using the Numpy package. However, as soon as I use 128-bit integers or bigger, I start getting negative values.

Its working fine with integers like 888888888888888. All I need to do is to set the datatype as np.int64, but for larger values none of the data types are working.

I am using Numpy because of speed. And another reason is that I am not that perfect in programming. Any solution to this? Is it possible to define custom datatype in Numpy or using python default datatype in this code?

Here is the code:

JavaScript

Advertisement

Answer

The source of the negative value is coming from integer overflows. If you want to prevent overflows, you should use sufficiently big integers. Beyond 64 bits, Numpy only support unbounded Python integers (which are not very fast). You can enable this with dtype=object.

Here the corrected code:

JavaScript

Output:

JavaScript
Advertisement