Possible optimization in my code?

前端 未结 3 809
孤城傲影
孤城傲影 2020-12-18 14:06

In order to solve the Euler Project problem n°5, I wrote the following program:

class p5
{
    const int maxNumber = 20;
    static void Main(string[] args)
         


        
3条回答
  •  攒了一身酷
    2020-12-18 14:39

    Using Enumerable is slow (see this for comparison of Enumerable.Repeat and for loop for initialization of an array). Try plain while/for loop like this:

            int maxNumber = 21;
            int n = 1;
            bool found = false;
            while(!found)
            {
                found = true;
                for(int i = 1; i < maxNumber; i++)
                {
                    if(n % i != 0)
                    {
                        found = false;
                        break;
                    }
                }
                n++;
            }
            return n-1;
    

    This runs for about 4 seconds on my computer in debug.

    EDIT

    When considering further optimizations, it is better to start testing modulo of larger numbers, so when I changed the for loop to:

    for (int i = maxNumber; i > 1; i--)
    

    the time dropped to under 2 seconds.

    A mathematical insight would be that we only have to test divisibility by numbers that are not multiples of the numbers we already tested. In our case we can write:

        private int[] p = { 19, 17, 16, 13, 11, 9, 7, 5, 4, 3, 2 };
        int Job()
        {
            int n = 1;
            bool found = false;
            while (!found)
            {
                found = true;
                foreach (int i in p)
                {
                    if (n % i != 0)
                    {
                        found = false;
                        break;
                    }
                }
                n++;
            }
            return n - 1;
        }
    

    However, this is actually slower, about 2.5 seconds.

提交回复
热议问题