K
K
K A2019-02-24 01:21:57
Algorithms
K A, 2019-02-24 01:21:57

An array of powers of two in C#, did you do it right?

The code works, optimization is interesting.

using System;

class ArrayTwo
{
    static void Main()
    {
        int size = 11;
        int k = 1;
        int[] nums = new int[size];
        for (int i = 0; i < nums.Length; i++)
        {
            nums[i] = k;
            Console.WriteLine(nums[i]);
            k += k;
        }
        Console.ReadKey();
    }
        
        
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Bashinsky, 2019-02-24
@BashkaMen

Here is my option

var size = 10;
var nums = Enumerable.Range(1, size).Select(s => Math.Pow(2, s)).ToArray();

K
Kirill Vlasov, 2019-02-24
@Neikist

Specifically for degrees of two, you can look at bit shifts. Shift to the left is essentially a multiplication by 2. Although I doubt that there will be any gain.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question