Java has limitations when it comes to primitive data types. If your long or double are too big, then it will overflow into a negative number. Try using the BigInteger class for storing larger numbers.
Check this out:
How does Java handle integer underflows and overflows and how would you check for it?