0

When trying to write a truthtable I tried to figure out the algorithm, and I found one that works. However now I don't understand why it doesn't throw a ArithmeticException.

for(int i=0; i<Math.pow(2, numberOfInputs()); i++)
    {
        for(int j=0; j<numberOfInputs(); j++)
        {
            System.out.print("" + i/(int) Math.pow(2, j)%2 + "\t");

        }
        System.out.println("");
    }

When trying this with numberOfInputs() returning 2, I get:

Truthtable
0   0   
1   0   
0   1   
1   1   

But I dont't understand how this can be since Math.pow(2, j)%2 will be =0 multiple times?!

Andronicus
  • 25,419
  • 17
  • 47
  • 88
SVJ
  • 1

1 Answers1

2

It's because of the precedence, this is executed first: i/(int) Math.pow(2, j), then modulo. The first expression is never a division by zero. More about it in the documentation.

Andronicus
  • 25,419
  • 17
  • 47
  • 88