tags:

views:

119

answers:

3

ok so I'm just getting started in scala.. ran into a weird problem with a large number.

import Math._
var num:Long=0
num+=600851475
num*=1000
println(num)

that code works fine, yet the following doesn't compile with an error saying the integer is too large.

import Math._
var num:Long=0
num+=600851475000
println(num)

what's up? can scala not handle a 12-digit number? :/

+4  A: 

Your constant should be 600851475000L

DigitalRoss
+2  A: 

Without L (or l) suffix, the literal's value is treated as a 32-bit int.

Laurence Gonsalves
+8  A: 

Even though num is declared to be a Long, 600851475000 is read by the compiler to be an Int, which can only handle numbers in [-2^32, 2^32) [-2^31, 2^31). Writing the number as 600851475000L tells the compiler to treat it as a Long, which will handle numbers up to about 18 digits.

Hoa Long Tam
@Hoa Long Tam - Int's range is actually [-2^31, 2^31), but the point is otherwise right on target.
Rex Kerr
For precisely representing numbers that even Long can't handle, there is scala.BigInt (in the standard library). You still can't write 37-digit literals, but BigInt can be constructed from a String, so you can fake it (just wrap the 37-digit literal in quotes).
David Winslow
@Rex Kerr - Thanks for catching that!
Hoa Long Tam