摘要和循环

时间:2012-06-26 13:23:45

标签: math loops sum

我正在读一篇文章,这篇文章有很多公式。它有几个sumatories(我的意思是这样:ΣhΣi)我可以把它写成两个嵌套for循环吗?

像:

for (h=1; h<=5; h++){
    for(i=1; i<=5; i++){
        sum+=i;
    }
}

感谢您的耐心:)

1 个答案:

答案 0 :(得分:1)

如果你看一下例子11 here

 Sum(Sum(x*y)) = Sum(x)*Sum(y)

左侧可以写为嵌套for循环:

for(x goes 1 to n)
  for(y goes 1 to m)
    add to the result (x*y)

右侧可以写成两个独立的循环。

for(x goes 1 to n)
  add to the firstResult (x)
for(y goes 1 to m)
  add to the secondResult (y)
set result to firstResult * secondResult

右侧提高了时间效率O(n * m)vs O(n + m),但是花费了一些空间(保持第一和第二结果)。