2015-10-31 90 views
1

我注意到currentTimeMillis方法工作不正確。即使應用在30秒內計算了階乘,其差異始終爲3System.currentTimeMillis在Scala中無法正常工作

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

您的代碼對我來說很好。你介意分享你如何執行你的代碼嗎?在任何IDE或命令行中的'scalac'或...?您計算的30秒可能包含編譯時間,運行代碼只需3秒鐘。 –

+0

我使用IntelliJ IDEA Scala插件。 – barbara

回答

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