我注意到currentTimeMillis
方法工作不正常。即使应用在30
秒内计算出一个阶乘,但差异始终为3
。
object Main extends App {
def factorial(n: BigInt) = {
val start = currentTimeMillis()
@tailrec
def rec(acc: BigInt, n: BigInt): BigInt = if (n <= 1) acc else rec(n * acc, n - 1)
val fac: BigInt = rec(1, n)
val end = currentTimeMillis()
((end - start) / 1000, fac)
}
val res = factorial(100000)
println(s"Get ${res._2} \n in ${res._1} seconds")
}
我的代码有什么问题?为什么会返回错误的结果?
答案 0 :(得分:2)
您的代码没有任何问题。对我来说,输出似乎是正确的:
import java.lang.System.currentTimeMillis
import scala.annotation.tailrec
object Main extends App {
def factorial(n: BigInt) = {
val start = currentTimeMillis()
@tailrec
def rec(acc: BigInt, n: BigInt): BigInt = if (n <= 1) acc else rec(n * acc, n - 1)
val fac: BigInt = rec(1, n)
val end = currentTimeMillis()
((end - start) / 1000, fac)
}
def printTimeForFactorial(n: BigInt) = {
val res = factorial(n)
println(s"Factorial of ${n} took ${res._1} seconds")
}
printTimeForFactorial(1)
printTimeForFactorial(1000)
printTimeForFactorial(10000)
printTimeForFactorial(50000)
printTimeForFactorial(100000)
printTimeForFactorial(110000)
printTimeForFactorial(120000)
}
打印
Factorial of 1 took 0 seconds
Factorial of 1000 took 0 seconds
Factorial of 10000 took 0 seconds
Factorial of 50000 took 1 seconds
Factorial of 100000 took 5 seconds
Factorial of 110000 took 6 seconds
Factorial of 120000 took 7 seconds