简化从环求和使用if说明书 [英] Simplifying Summation from loop with an if statment
问题描述
我无法搞清楚如何简化code来求和,因为它有一个if语句了。
I'm having trouble figuring out how to simplify this code to summations since it has an if statement in it.
sum=0
for (i = 1 to n ){
for (j = 1 to i^2){
if (j % i ==0) then
for (k = 1 to j){
sum++
}
}
}
}
我知道,if语句将执行我次,每次循环。
I know the if statement will execute i times every loop.
1%1 = 0
2%2 = 0
4%2 = 0
3%3 = 0
6%3 = 0
9%3 = 0
等等。
这是我目前为止(见下面的链接),原谅我^ 2的符号,我不能发表图片还没有代表。此外,内部总和为i ^ 2不2选择我。
This is what I have so far (see link below), forgive the i^2 notation, I can't post images yet without rep. Again, the inner summation is i^2 not 2 choose i.
<一个href="http://www.HostMath.com/Show.aspx?$c$c=%5Csum%5Climits_%7Bi%3D1%7D%5En%5Csum%5Climits_%7Bj%3D1%7D%5Ei%5E%7B2%7D%20%5Csum%5Climits_%7Bk%3D1%7D%5Ej%0A(1)" rel="nofollow">http://www.HostMath.com/Show.aspx?$c$c=%5Csum%5Climits_%7Bi%3D1%7D%5En%5Csum%5Climits_%7Bj%3D1%7D%5Ei%5E%7B2%7D%20%5Csum%5Climits_%7Bk%3D1%7D%5Ej%0A(1)
我想简化的内求和到j,但它只发生岛次。我觉得这是很简单的,我没有看到明显的联系。
I want to simplify the inner summation to j, but it only happens, i times. I feel like this is very simple and I am not seeing the obvious connection.
推荐答案
这是我提出的解决方案:
That is my proposed solution:
sum=0
for (i = 1 to n )
{
for (j = i to i^2, step=i){
sum = sum + j
}
}
更新 它看起来像方锥体数量,所以你可以这样写:
UPDATE It looks like square pyramidal number, so you can just write:
sum = (2*n^3 + 3*n^2 + n / 6)
这篇关于简化从环求和使用if说明书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!