-4

http://projecteuler.net/problem=1

3または5の倍数である10未満のすべての自然数をリストすると、3、5、6、および9になります。これらの倍数の合計は23です。1000未満の3または5のすべての倍数の合計を求めます。

「intmaxNum」を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のすべての乗数の合計を見つけることです。配列からの個別の数値を合計します。

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

問題は、いくつかの数字を2回数えることです。たとえば、最初に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 に答える