Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the modulo operator for longs in Java?

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 but it didn't work. Do I have to convert it to a BigInteger and use the remainder method? Thanks.

like image 983
Descartes Avatar asked Apr 20 '11 23:04

Descartes


People also ask

What is the modulo operator in Java?

The modulo operator is used to compute the remainder of an integer division that otherwise lost. It's useful to do simple things like figuring out if a given number is even or odd, as well as more complex tasks like tracking the next writing position in a circular array.

What types does the MOD (%) work on?

3) modulus operator is not just applicable to integral types e.g. byte, short, int, long but also to floating-point types like float and double. 4) You can also use the remainder operator to check if a number is even or odd, or if a year is leap year.

What is the use of modulus (%) operator?

The modulus operator is added in the arithmetic operators in C, and it works between two available operands. It divides the given numerator by the denominator to find a result. In simpler words, it produces a remainder for the integer division. Thus, the remainder is also always an integer number only.

What is the time complexity of modulo operation?

Modulo/remainder is a O(1) operation (it's essentially just a variation on division, which takes constant time on fixed-sized numbers). Therefore, the inside of the loop is an O(1) operation, which makes the total complexity O(√n) .


2 Answers

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?

like image 60
Daniel Lubarov Avatar answered Sep 21 '22 13:09

Daniel Lubarov


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.

like image 27
corsiKa Avatar answered Sep 19 '22 13:09

corsiKa