0
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)。有任何想法吗?

编辑:好的,所以大约错了 33000。无论如何,这是我修改后的代码。

4

2 回答 2

0

你少了33000。

您的问题是您计算了可以被 3 和 5 整除的数字两次。

您需要重新设计循环以避开这些数字,或者在第二个循环中检查该数字是否不能被 3 整除。如果是,则不要将其相加。

于 2013-09-11T20:25:22.370 回答
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);
于 2013-09-11T20:28:49.777 回答