Algorithm LogbookAlgorithm Logbook

Time Complexity Intro

Analysis

๐Ÿ“‹ Problem Statement

Write a function that calculates the sum of all natural numbers from 1 to N. Implement two approaches: a loop-based O(N)O(N) solution and a formula-based O(1)O(1) solution using the Gauss identity N(N+1)2\frac{N(N+1)}{2}.

๐Ÿ’ก Intuition

This problem introduces time complexity by showing two algorithms that produce identical results but with vastly different performance. The brute-force loop visits every number in O(N)O(N) time. The Gauss formula โˆ‘i=1Ni=N(N+1)2\sum_{i=1}^{N} i = \frac{N(N+1)}{2} computes the answer in O(1)O(1) โ€” instantly regardless of NN.

๐Ÿ”ง Approach

  1. Approach A (Loop): Initialize total = 0. Loop from 1 to N, adding each number. Return total.
  2. Approach B (Math): Use the formula N(N+1)2\frac{N(N+1)}{2} with integer division. This is a single operation.
  3. Compare: For N=1,000,000N = 1{,}000{,}000, Approach A performs 1 million additions. Approach B performs 1 multiplication and 1 division.

โšก Complexity Analysis

Time

O(N)O(N) for the loop approach; O(1)O(1) for the mathematical formula

Space

O(1)O(1) for both approaches โ€” only a single variable is used

โš ๏ธ Common Mistakes

  • Using floating-point division / instead of integer division // in the formula, leading to precision issues for large NN
  • Off-by-one error: using range(1, n) instead of range(1, n + 1) in the loop
  • Not recognizing that the formula can overflow in languages with fixed integer sizes (not an issue in Python)

๐ŸŽฏ Final Thoughts

This is your first lesson in algorithmic thinking: the same problem can be solved in dramatically different ways. Always ask "Is there a mathematical shortcut?" before writing a loop. Understanding O(N)O(N) vs O(1)O(1) here sets the stage for everything that follows.