Search code examples
twos-complementarithmetic-expressions

Which arithmetic properties do two's complement integers have?


There are multiple arithmetic properties that hold for Whole Numbers, the ones we're used to when performing calculations:

  • '+' Commutativity: a+b == b+a
  • '+' Associativity: (a+b)+c == a+(b+c)
  • '*' Commutativity: a*b == b*a
  • '*' Associativity: (a*b)*c == a*(b*c)
  • Distributivity of '*' over '+': a*(b+c) == a*b + a*c

I know that commutativity relations hold for the two's complement integers. But I'm not sure about the other properties.

Which of the properties above are satisfied by two's complement integers. If the result depends on signedness I would like to know that as well.


Solution

  • I wrote a program that checks every 8-bit integer. Since the search space is not that big I could check every single 8-bit two's complement integer. It's not a rigorous mathematical proof but worked well for my purposes

    for(I8 x = 0; x != int8Max; ++x){
        for(I8 y = 0; y != int8Max; ++y) {
          for(I8 z = 0; z != int8Max; ++z) {
            I8 t1=x+y;
            I8 r1=t1*z;
            I8 t2=x*z;
            I8 t3=y*z;
            I8 r2=t2+t3;
            if(r1!=r2) {
              printf("Achtung!!\n");
              break;
            }
          }
        }
      }
    

    I used program like this to verify the truthness of values, slightly modifying the program for each case.

    I found that both signed and unsigned integers have all of the properties listed above:

    • Associativity for + and * operations
    • Commutativity for + and * operations
    • Distributivity of * over +