0

今夜、私はhttp://projecteuler.net/problem=1の問題 1 に取り組んでいました。while ループを使用しても機能しません。2 つのショートカット if ステートメントを使用して動作させました。正しく解決した後、フォーラムで数学を使用したより良い解決策があることがわかりましたが、私は新しく、while ループで何が問題になったのかを学ぶ必要があります。

ここに問題があります: 3 または 5 の倍数である 10 未満の自然数をすべて列挙すると、3、5、6、および 9 になります。これらの倍数の合計は 23 です。3 または 5 の倍数のすべての合計を見つけます。 5 1000 未満。正解 = 233168

    public class Project1_Multiples_of_3_and_5 {
//Main method
public static void main (String args[])
{   
    int iResult = 0;

    for (int i = 1; i <= 1000 / 3; i++)  // for all values of i less than 333 (1000 / 3)
    {
        iResult += i * 3;  // add i*3 to iResults
        //the short cut if below works but I want to use a while loop
                //iResult +=  (i % 3 !=0 && i < 1000 / 5) ? i * 5 : 0;  // add i*5 to iResults excluding the multiples 3 added in the previous step while i < 200 ( 1000 / 5 )

        while ( (i < 1000 / 5) && (i % 3 != 0) )
        {
            iResult += i * 5;
/************************************************************************************
SOLVED!!! ... sort of
adding a break makes the code work but defeats the purpose of using a loop.  I guess     I    should just stick with my 2 if statements
************************************************************************************/

                        break;
        }//end while
    }// end for

    System.out.println(iResult);

    }//end main method
}//end class
4

1 に答える 1

6

終了条件で while変数 ( ) を変更しないため、ループが終了することはありません。i

while ( (i < 1000 / 5) && (i % 3 != 0) )
{
    iResult += i * 5; // i is not updated here
}//end while

また、2 番目の条件により、3 の倍数が検出されるとすぐにループが終了しますが、これはおそらく望ましくありません。
1 つのアイデアは、これをfor3 の倍数のループに変更することです (最初のforループの外に移動します)。

于 2013-05-11T23:25:48.333 に答える