所以Scala应该和Java一样快。我正在重温Scala中的一些Project Euler问题,这些问题我最初是在Java语言中解决的。具体来说,问题5:“能被从1到20的所有数字整除的最小正数是多少?”
这是我的Java解决方案,在我的机器上需要0.7秒才能完成:
public class P005_evenly_divisible implements Runnable{
final int t = 20;
public void run() {
int i = 10;
while(!isEvenlyDivisible(i, t)){
i += 2;
}
System.out.println(i);
}
boolean isEvenlyDivisible(int a, int b){
for (int i = 2; i <= b; i++) {
if (a % i != 0)
return false;
}
return true;
}
public static void main(String[] args) {
new P005_evenly_divisible().run();
}
}
下面是我“直接翻译”成Scala的代码,它需要103秒(147倍的时间!)
object P005_JavaStyle {
val t:Int = 20;
def run {
var i = 10
while(!isEvenlyDivisible(i,t))
i += 2
println(i)
}
def isEvenlyDivisible(a:Int, b:Int):Boolean = {
for (i <- 2 to b)
if (a % i != 0)
return false
return true
}
def main(args : Array[String]) {
run
}
}
最后是我对函数式编程的尝试,它需要39秒(55倍的时间)
object P005 extends App{
def isDivis(x:Int) = (1 to 20) forall {x % _ == 0}
def find(n:Int):Int = if (isDivis(n)) n else find (n+2)
println (find (2))
}
在Windows 7 64位平台上使用Scala 2.9.0.1。如何提高性能?我做错了什么吗?还是说Java只是快了很多?
https://stackoverflow.com/questions/6146182
复制相似问题