解决项目欧拉#1

时间:2014-10-26 13:05:27

标签: c#

项目中的问题欧拉说:

  

如果我们列出10以下的所有自然数是3或5的倍数,我们得到3,5,6和9.这些倍数的总和是23.

     

查找低于1000的3或5的所有倍数的总和。

当我用数字<来测试它时10,它计算23,但当我尝试1000时,它给出了错误的答案。请帮助:)

代码:

    using System;
    using System.Diagnostics;
    using System.Collections.Generic;

namespace Test
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            //Initialisation
            Console.WriteLine ("==============================");
            Console.WriteLine ("Project Euler - Problem 1 - Multiples of 3 and 5 - Test");
            Console.WriteLine ("Initialising");
            Stopwatch stopwatch = new Stopwatch ();
            stopwatch.Start ();
            Console.WriteLine ("==============================");

            HashSet<int> list = new HashSet<int> (); //Creates a list

            int sum = 0;

            //Add every multiple of 3 to the list
            for (int x = 3; x < 10; x = x + 3) {
                list.Add (x); 
            }

            //Add every multiple of 5 to the list
            for (int y = 5; y < 10; y = y + 5) {
                list.Add (y);
            }

            //Remove every duplicate from the list
            for (int z = 15; z <= 1000; z = z +15) {
                list.Remove (z);
            }

            foreach (int x in list) {
                sum = sum + x;
            }

            //Termination
            Console.BackgroundColor = ConsoleColor.DarkRed;
            Console.WriteLine ("==============================");
            stopwatch.Stop ();
            Console.WriteLine ("Time elapsed: {0}", stopwatch.Elapsed);
            Console.WriteLine ("==============================");
            Console.WriteLine ("Sum: " + sum);
            Console.WriteLine ("==============================");
            Console.WriteLine ("Terminating");
            Console.WriteLine ("==============================");
        }
    }
}

3 个答案:

答案 0 :(得分:4)

您正在使用HashSet

  

HashSet是一个包含唯一元素的无序集合

它不存储重复的条目。你不需要删除它。

只需删除您的第3个for loop

答案 1 :(得分:1)

您可以拥有一个并使用模数运算符,而不是具有多个for循环。这将使您添加的重复项无效。

for(int i = 0; i < 1000; ++i)
{
    if(i % 3 == 0 || i % 5 == 0)
    {
        // Add to list
    }
}

答案 2 :(得分:0)

您无需删除15的倍数:

const int N = 1000;

//Add every multiple of 3 to the list
for (int x = 3; x < N; x += 3) {
     list.Add(x); 
}

//Add every multiple of 5 to the list
for (int y = 5; y < N; y += 5) {
    list.Add(y);
}

int sum = list.Sum();