0

编辑问题是找到像 1,3,6,10,15 这样的数字的除数,它遵循 n*(n+1)/2 模式。我得到了答案,谢谢

我正在由一位经验丰富的程序员浏览以下代码片段。

int number = 0;
int i = 1;

while(NumberOfDivisors(number) < 500){
    number += i;
    i++;

我尝试了很多,但我无法理解以下代码部分。

number += i;
i++;

为什么他不只是增加数字本身?如果他使用相同的代码,执行过程中不会丢失一些数字吗?其背后的逻辑是什么?

这是其余的代码

private int NumberOfDivisors(int number) {
    int nod = 0;
    int sqrt = (int) Math.Sqrt(number);

    for(int i = 1; i<= sqrt; i++){
        if(number % i == 0){
            nod += 2;
        }
    }
    //Correction if the number is a perfect square
    if (sqrt * sqrt == number) {
        nod--;
    }

    return nod;
}

我理解了上面的部分。看不懂第一部分。

正如其中一个答案所说,迭代看起来像这样:

NumberOfDivisors(0)
    0 += 1
NumberOfDivisors(1)
    1 += 2
NumberOfDivisors(3)
    3 += 3
NumberOfDivisors(6)

等等

他为什么要消除2,4,5等???

4

4 回答 4

2

原作者这样做是为了解决这个问题:500 个除数的三角形数。按照链接获取解释,您发布的代码甚至在那里......

The sequence of triangle numbers is generated by adding the natural numbers.
So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, …
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?
于 2012-09-16T14:19:12.137 回答
1

他不只是增加它。他在添加 i ,每次都会变大。

+= 1;
+= 2;
etc.
于 2012-09-16T14:03:57.957 回答
1

迭代看起来像这样:

NumberOfDivisors(0)
    0 += 1
NumberOfDivisors(1)
    1 += 2
NumberOfDivisors(3)
    3 += 3
NumberOfDivisors(6)

等等

于 2012-09-16T14:04:30.810 回答
0

这是某种启发式方法,因为除数的数量呈非线性增长,最好以非线性顺序检查数字。我看不出它与近似增长率的关系,可能只是作者的随机直觉选择。

于 2012-09-16T14:13:46.180 回答