1

I am looking at the following piece of code in Java:


public class MyClass {
    public static void main(String args[]) {
      int mod = (int) (1e9) + 7;
      int curValue = 483575207;
      int numFullRow = 237971068;
      long profit1 = 995913967;
      long profit2 = profit1;
      int numSameColor = 3;
      profit1 %= mod;
      profit2 %= mod;
      profit1 += (long)(curValue + curValue - numFullRow + 1) * numFullRow / 2 * numSameColor;
      System.out.println(profit1 % mod);
      profit2 += ((long)(curValue + curValue - numFullRow + 1) *numFullRow / 2 * numSameColor) % mod;
      System.out.println(profit2);
      
    }
}

The output of profit1 and profit2 turned out to be different which I do not quite understand. profit2 does not work as expected.

1

1 Answer 1

2

The += operator is messing with the order of operations. In this case, profit2 is doing the mod before adding to the existing profit2, and profit one is accumulating before executing the mod operator.

You can read more about java operator precedence here: https://introcs.cs.princeton.edu/java/11precedence/

If you expand the += step and create a profit3 as in this example, you can understand the order of operations:

int mod = (int) (1e9) + 7;
      int curValue = 483575207;
      int numFullRow = 237971068;
      long profit1 = 995913967;
      long profit2 = profit1;
      long profit3 = profit1;
      int numSameColor = 3;
      profit1 %= mod;
      profit2 %= mod;
      long temp = (long)(curValue + curValue - numFullRow + 1) * numFullRow / 2 * numSameColor;
      profit3 = profit3 + (temp % mod);
      profit1 += temp;
      System.out.println(profit1 % mod);
      profit2 += ((long)(curValue + curValue - numFullRow + 1) *numFullRow / 2 * numSameColor) % mod;
      System.out.println(profit2);
      System.out.println(profit3);

https://replit.com/@notoreous/modconversion#Main.java

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.