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.
Asked
Active
Viewed 4.2k times
3 Answers
22
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?

Daniel Lubarov
- 7,796
- 1
- 37
- 56
-
Okay, the following code is inside a for loop and total is a BigInteger. `code` total = total.add(BigInteger.valueOf(b(i)%1234567891011) `code` – Descartes Apr 20 '11 at 23:05
-
Might you need an L at the end of 1234567891011? Assuming b(i) returns a long as well. – Marvo Apr 20 '11 at 23:07
-
Yeah, just stick an "L" on the end of 1234567891011 to tell the compiler it's a long literal (otherwise the compiler will treat it as an int literal). – Daniel Lubarov Apr 20 '11 at 23:07
6
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.

corsiKa
- 81,495
- 25
- 153
- 204
0
You can also try working with the BigInteger class which has a remainder() method that works similarly to %.

elekwent
- 763
- 5
- 10
-
His question states that this is already a possibility but he doesn't want to do this. – alternative Apr 20 '11 at 23:42
-
You're right. I missed that in his question. I'll leave my answer the way it is though, as sort of an awkward answer to him asking "Do I have to convert it to a BigInteger and use the remainder method?". – elekwent Apr 21 '11 at 00:18
-
Another way to read my answer above... Yes, you can also try working with the BigInteger class, which has a remainder() method that works similarly to %. You see what I did? I add a yes and two commas, and now it answers his question perfectly. – elekwent Apr 21 '11 at 00:23