Powers of two

O(n)

A power of two is a number of the form 2^k for a non-negative integer k. Starting from 2⁰ = 1, each successive term is exactly double the previous one. Powers of two are ubiquitous in computer science: they determine bit widths, memory sizes, and hash-table capacities. After 16 doublings, 2¹⁶ = 65 536 — well within JavaScript safe-integer range.

Sequence
Press ▶ to run
Edit the input and press Play

How it works

  1. Initialize the array with [1], representing 2⁰ = 1
  2. For each k from 1 to n, double the previous value to get 2^k
  3. Append 2^k to the array and highlight the new term
  4. Mark the final term 2^n green when the sequence is complete

Pseudocode

1powersOfTwo(n):                      # O(n)2  result ← [1]        # 2^0 = 13  for k = 1 to n:4    result.push(result.last * 2)     # 2^k = 2^(k-1) × 25  return result