int x = 0;
int y = 0;
int z = 0;
int w = 0;
int v = 0;
while ((x + 3) < 1000)
{
x = (x + 3);
if ((x % 15) != 0)
{
w = (w + x);
}
}
while ((y + 5) < 1000)
{
y = (y + 5);
z = (z + y);
}
v = (w + z);
System.out.println("w = " + w);
System.out.println("z = " + z);
System.out.println("v = " + v);
我知道它真的很草率,但我无法弄清楚为什么输出不正确(关闭大约100-200)。有什么想法吗?
编辑:好的,大约33,000错了。无论如何,这是我修改后的代码。
答案 0 :(得分:0)
你被33万人拒之门外。
你的问题是,你计算可被3和5两次整除的数字。
您需要重新设计循环以避开这些数字,或者在第二个循环中检查数字是否可以被3整除。如果是,则不要将其添加。< / p>
答案 1 :(得分:0)
您是否考虑过使用%
(模数)运算符?这对欧拉问题很有帮助。
int sum = 0;
for(int i = 3; i < 1000; i++)
{
if(i%3 == 0 || i%5 == 0)
{
sum = sum + i;
}
}
System.out.println(sum);
但要看到你的问题:
int total = 0;
int threes = 0;
int fives = 0;
int total = 0;
int mutually_exclusive = 0;
//collect all divisible by 3
while (threes < 1000)
{
//find mutually exclusive
if(threes % 5 == 0)
{
mutually_exclusive = mutually_exclusive + threes;
}
total = total + threes;
threes = threes + 3;
}
while (fives < 1000)
{
total = total + fives ;
fives = fives + 5;
}
//delete mutually exclusive to avoid duplicates
total = total - mutually_exclusive;
System.out.println("total = " + total);