项目欧拉:问题1(可能的重构和运行时优化)重构、欧拉、项目、问题

2023-09-10 23:40:34 作者:瘦够了

我已经听到了很多关于项目欧拉所以我想我解决了在C#中的问题之一。如在网站上所列的问题如下:

I have been hearing a lot about Project Euler so I thought I solve one of the problems in C#. The problem as stated on the website is as follows:

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

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.

找到3所有倍数的总和   或5千以下。

Find the sum of all the multiples of 3 or 5 below 1000.

我写我的code如下:

I wrote my code as follows:

  class EulerProblem1
    {
        public static void Main()
        {
            var totalNum = 1000;
            var counter = 1;
            var sum = 0;

            while (counter < totalNum)
            {
                if (DivisibleByThreeOrFive(counter))
                    sum += counter;

                counter++;
            }

            Console.WriteLine("Total Sum: {0}", sum);
            Console.ReadKey();
        }

        private static bool DivisibleByThreeOrFive(int counter)
        {
            return ((counter % 3 == 0) || (counter % 5 == 0));

        }
    } 

这将是巨大的,获得替代的实现一些想法少冗长/更清晰的语法,更好的优化。这些想法可能会快速和肮脏的变化,以带出大炮消灭蚊子。其目的是探索计算机科学的深处,而试图改善这一特别琐碎code段。

It will be great to get some ideas on alternate implementations with less verbosity/cleaner syntax and better optimizations. The ideas may vary from quick and dirty to bringing out the cannon to annihilate the mosquito. The purpose is to explore the depths of computer science while trying to improve this particularly trivial code snippet.

感谢

推荐答案

使用LINQ(更新中评论建议)

With LINQ (updated as suggested in comments)

static void Main(string[] args)
{
    var total = Enumerable.Range(0,1000)
                    .Where(counter => (counter%3 == 0) || (counter%5 == 0))
                    .Sum();

    Console.WriteLine(total);
    Console.ReadKey();
}