What is the modulo operator for longs in Java?

前端 未结 3 1377
清酒与你
清酒与你 2021-01-11 10:25

How do I find the modulo (%) of two long values in Java? My code says \'Integer number too large\' followed by the number I\'m trying to mod. I tried casting it to a long bu

相关标签:
3条回答
  • 2021-01-11 10:30

    You can also try working with the BigInteger class which has a remainder() method that works similarly to %.

    0 讨论(0)
  • 2021-01-11 10:37

    The % operator does work for longs. It sounds like you may have forgotten to stick L at the end of a numeric literal, as in 123456789L. Can we see your code?

    0 讨论(0)
  • 2021-01-11 10:49

    You can only have an integer up to 2 147 483 647. If you want to go bigger than that, say 3 billion, you must specify it to be a long

    class Descartes {
        public static void main(String[] args) {
            long orig = Long.MAX_VALUE;
            long mod = orig % 3000000000; // ERROR 3000000000 too big
            long mod = orig % 3000000000L; // no error, specified as a long with the L
        }
    }
    

    Keep in mind that you can use capital OR lowercase L, but it's advisable to use capital, since the lowercase looks remarkably similar to the number 1.

    0 讨论(0)
提交回复
热议问题