问题陈述:
Scala.Long应该将正整数处理为9223372036854754775807,但是scalafiddle.io仅允许10 ^ 9数量级的整数
参考:
https://www.scala-lang.org/api/2.12.6/scala/Long.html
https://www.tutorialspoint.com/scala/scala_data_types.htm
代码:
def fib(n:Int):Long={
@tailrec def fibTail( n: Int, a:Int, b:Int): Long = n match {
case 0 => a
case _ => fibTail( n-1, b, a+b )
}
return fibTail( n, 0, 1)
}
//test cases
for (tryit<-1 to 10) println(tryit + ": " + fib(tryit))
for (breakit<-10 to 100 by 10) println(breakit + ": " + fib(breakit))
for (overflow<-1 to 8) println("10^" + overflow + ": " + fib(math.pow(10,overflow).toInt))
scalafiddle.io上的代码输出]
斐波那契
1:12:13:24:35:56:87:138:219:3410:5510:5520:676530:83204040:10233415550:-29863286360:182052936070:88544475180:-28500738790:-1581614984100:-98010732510 ^ 1:5510 ^ 2:-98010732510 ^ 3:155611143510 ^ 4:124204489110 ^ 5:87387609110 ^ 6:188475513110 ^ 7:-144873594110 ^ 8:1819143227
问题:
这是scalafiddle环境的人工产物,还是我做错了其他事情?
问题陈述:Scala.Long应该处理9223372036854775807的正整数,但是scalafiddle.io仅允许10 ^ 9数量级的整数。参考:https://www.scala-lang.org/api/2.12 ....] >
您不是在Long
上进行计算,而是在各处使用Int
,并且仅在完成后才将结果扩展到Long
。如果您实际使用Long
,则如下所示:
def fib(n:Long):Long={
@tailrec def fibTail( n: Long, a:Long, b:Long): Long = n match {
case 0 => a
case _ => fibTail( n-1, b, a+b )
}
return fibTail( n, 0, 1)
}