为什么是
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 毫秒