-4

http://projecteuler.net/problem=1

如果我们列出所有小于 10 且是 3 或 5 的倍数的自然数,我们会得到 3、5、6 和 9。这些倍数的和是 23。求出 1000 以下的所有 3 或 5 的倍数之和。

如果我将“int maxNum”更改为 10 或任何其他小数字(如 20),我将得到正确答案。

但不知何故,当我用一个像 1000 这样的大数字做它时,它会给我一个我不希望出现的数字,我不知道为什么,请帮忙。

它这样做是因为它已经达到了 int 的最大值吗?

class Program
{


    static void Main(string[] args)
    {
        //TASK: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
        //Find the sum of all the multiples of 3 or 5 below 1000.

        int multiplierA = 3;
        int multiplierB = 5;

        int maxNum = 1000;
        int i = 1;

        int deelEen = MultiplyFactory(multiplierA, i, maxNum);
        int deelTwee = MultiplyFactory(multiplierB, i, maxNum);

        int result = deelEen + deelTwee;

        Console.WriteLine(result);
        Console.Read();
    }

    static int MultiplyFactory(int multiplier, int i, int maxNum)
    {
        List<int> savedNumbers = new List<int>();
        while(multiplier*i < maxNum)
        {
            savedNumbers.Add(multiplier*i);
            i++;
        }

        int answer = 0;
        foreach(int getal in savedNumbers)
        {
            Console.WriteLine(getal);
            answer = answer + getal;
        }
        savedNumbers.Clear();
        return answer;

    }
}
4

2 回答 2

1

我认为问题在于你需要找到所有 3 或 5 的倍数的总和。你的程序正在做的是找到 3 的所有乘数的总和 + 5 的所有乘数的总和。你可以返回 int 数组,然后对数组中的不同数字求和。

您还可以使用 Linq 从列表中获取不同的值

class Program
{
    static void Main(string[] args)
    {
        //TASK: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
        //Find the sum of all the multiples of 3 or 5 below 1000.

        int multiplierA = 3;
        int multiplierB = 5;

        int maxNum = 1000;
        int i = 1;
        int result = 0;

        List<int> deelEen = MultiplyFactory(multiplierA, i, maxNum);
        List<int> deelTwee = MultiplyFactory(multiplierB, i, maxNum);

        foreach (int val in deelEen)
            result += val;

        foreach (int val in deelTwee)
            if (!deelEen.Contains(val)) result += val;

        Console.WriteLine(result);
        Console.Read();
    }

    static List<int> MultiplyFactory(int multiplier, int i, int maxNum)
    {
        List<int> savedNumbers = new List<int>();
        while (multiplier * i < maxNum)
        {
            savedNumbers.Add(multiplier * i);
            i++;
        }

        return savedNumbers;

    }
}
于 2012-10-15T08:59:52.123 回答
0

问题是你数了一些数字两次。例如,您首先将 15 相加为可被 3 整除,然后将其相加为可被 5 整除。

所以对于 1 到 20 之间的数字,你有

deelEen = 3 + 6 + 9 + 12 + 15 + 18
deelTwee = 5 + 10 + 15

result = 3 + 5 + 6 + 9 + 10 + 12 + 15 + 15 + 18

当正确答案是

result = 3 + 5 + 6 + 9 + 10 + 12 + 15 + 18
于 2012-10-15T09:11:48.207 回答