1

I'm working on a function which takes in two ints like so: product(x, y) and returns the product of the two integers. Is there a way I could know that the product of these two ints will be a value larger than the value of INT32_MAX before I do the calculation so that I know there will be an error?

JaMiT
  • 14,422
  • 4
  • 15
  • 31
alex207e
  • 219
  • 1
  • 3
  • 6
  • 2
    Maybe store both ints in a 64 bit integer type, do the product, and compare against INT32_MAX? – cigien Sep 12 '20 at 01:11
  • How is sum related to a product here? – Slava Sep 12 '20 at 01:12
  • 1
    You mean `x * y` or `x + y`? – tadman Sep 12 '20 at 01:13
  • I meant product sorry, as in x * y. – alex207e Sep 12 '20 at 01:15
  • For `*`, and assuming a simple unsigned, it seems like if the sum of used bits (that is, position of MSB) per operand exceeds 32 then it would overflow. I might test that hypothesis on a few values.. as bits are power-of-two, and something something math about square roots. – user2864740 Sep 12 '20 at 01:16
  • For example, all in hex: FF*FF <= FFFF, 100*A0 > FFFF .. looking at the title, not practical implementations of detection-after :) – user2864740 Sep 12 '20 at 01:21
  • 1
    @user2864740 `0x7FFFFFFF * 0x00000000` will not overflow, so it's a little trickier. – tadman Sep 12 '20 at 01:22
  • Sum of bits (used through MSB) there is only 31 :D – user2864740 Sep 12 '20 at 01:23
  • @user2864740 two's complement is probably the same as unsigned 31 bit numbers, using absolute values – Slava Sep 12 '20 at 01:25
  • It's not clear this is a dup of the tagged question, which is asking about the SUM of 2 ints – Hong Ooi Sep 12 '20 at 04:06
  • A product of two integers is guaranteed to always fit the storage twice as big as its operands. So basically do what @cigien proposes, compute the product and store it in 64bit variable, compare agains INT32_MAX and if it fits, static_cast it to the smaller one and return, otherwise throw. – doomista Sep 12 '20 at 07:54
  • @doomista that sounds like an answer – Hong Ooi Sep 12 '20 at 08:32
  • both `+` and `*` have many duplicates: [How do I detect unsigned integer multiply overflow?](https://stackoverflow.com/q/199333/995714), [How do I detect overflow while multiplying two 2's complement integers?](https://stackoverflow.com/q/2713972/995714), [Catch and compute overflow during multiplication of two large integers](https://stackoverflow.com/q/1815367/995714), [Which way to test for signed integer overflow on multiply?](https://stackoverflow.com/q/23166648/995714)... – phuclv Sep 12 '20 at 13:07

0 Answers0