今夜、私は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