为什么是
for ( a <- 1 to 1000; b <- 1 to 1000 - a; c <- 1 to 1000 - a - b; if (a * a + b * b == c * c && a + b + c == 1000) ) println((a, b, c, a * b * c))
266毫秒
然后慢一点:
for (a <- 1 to 1000) for (b <- 1 to 1000 - a) for (c <- 1 to 1000 - a - b) if (a * a + b * b == c * c) if (a + b + c == 1000) println((a, b, c, a * b * c))
62毫秒
如果我理解正确,应该是一样的吗?
处理后的解决方案答案:
for ( a <- 1 to 1000; b <- 1 to (1000 - a) ) { val c = (1000 - a - b) if (a * a + b * b == c * c) println((a, b, c, a * b * c)) }
9毫秒
您的理解是错误的。
当条件在循环体内时,将发生以下情况:
// this for(x <- coll) if(condition) doSomething // will translate to coll.foreach{ x => if(condition) doSomething }
与条件本身在生成器中相反:
// this for(x <- coll if(condition)) dosomething // will translate to coll.withFilter(x => condition).foreach{ x => dosomething }
您可以查看Scala语言规范6.16了解更多详细信息。