简体   繁体   中英

How to reduce for loops to make code more efficient?

I am practicing C# and looking for code optimisation techniques. This code is giving the expected output and I want to write a more efficient code.

int test(int n)
{
    int sum = 0;
    for (int i = 1; i <= n; i++)
    {
        int p = 1;

        for (int j = 1; j <= i; j++)
        {
            p = 2 * p;
        }

        p = p + (2 * i * i);
        sum = sum + p;
    }
    return sum;
} 

I think that two for loops can be reduced to one but I can't figure out how to do it. Any advices?

You could use the bit shift left << operator instead of the j loop.

    int test(int n)
    {
        int sum = 0;
        for (int i = 1; i <= n; i++)
        {
            int p = 1 << i; // <= Here it is

            p += 2 * i * i;
            sum += p;
        }
        return sum;
    }

If you don't want to use bit shift you can use Math.Pow. Internally, computationally it is likely to cost same as the for loop you have, and bit shift could be better cost wise. Here is the alternate solution

        int test(int n)
        {
            int sum = 0;
            for (int i = 1; i <= n; i++)
            {
                int p = 1;

                p = (int)Math.Pow(2 * p, i);

                p = p + (2 * i * i);
                sum = sum + p;
            }
            return sum;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM