0

編集問題は、n*(n+1)/2 パターンに従う 1,3,6,10,15 のような数値の除数を見つけることでした。答えがわかりました、ありがとう

私は、経験豊富なプログラマーによる次のコード スニペットを試していました。

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;
}

上記の部分は理解できました。最初の部分が理解できません。

答えの1つが言ったように、反復は次のようになります。

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 に答える