Time Complexity Intro
๐ Problem Statement
Write a function that calculates the sum of all natural numbers from 1 to N. Implement two approaches: a loop-based solution and a formula-based solution using the Gauss identity .
๐ก 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 time. The Gauss formula computes the answer in โ instantly regardless of .
๐ง Approach
- Approach A (Loop): Initialize
total = 0. Loop from 1 to N, adding each number. Returntotal. - Approach B (Math): Use the formula with integer division. This is a single operation.
- Compare: For , Approach A performs 1 million additions. Approach B performs 1 multiplication and 1 division.
โก Complexity Analysis
for the loop approach; for the mathematical formula
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 - Off-by-one error: using
range(1, n)instead ofrange(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 vs here sets the stage for everything that follows.