Multiple algorithms for same problem
One Problem, Many Solutions
A fundamental idea in computer science is that there is rarely only one correct algorithm for a problem. Two different algorithms can accept the same inputs, follow completely different steps, and still produce the same correct output. Recognising this is important because it leads to the next question: if both are correct, which one is better - and for what reason? Understanding that alternatives exist is the first step towards being able to compare and choose between them.
Two Algorithms, One Problem
The tabs below show two algorithms that solve exactly the same problem: find the sum of the whole numbers from 1 to 3. Trace tables confirm both produce the output 6, but they reach that answer by entirely different routes.
Algorithm A uses a WHILE loop to add each number into a running total one at a time.
total ← 0
n ← 1
WHILE n <= 3
total ← total + n
n ← n + 1
ENDWHILE
OUTPUT total
Trace table (sequence = same row; WHILE = drop a line; two assignments inside the loop body are sequence, so same dropped row):
| total | n | OUTPUT |
|---|---|---|
| 0 | 1 | |
| 1 | 2 | |
| 3 | 3 | |
| 6 | 4 | |
| 6 |
When n becomes 4, the condition 4 <= 3 is false. The loop ends and OUTPUT total runs.
Algorithm B applies the mathematical formula: the sum of whole numbers 1 to n equals n × (n + 1) / 2. For n = 3: 3 × 4 / 2 = 6.
n ← 3 total ← n * (n + 1) / 2 OUTPUT total
Trace table (all three lines are sequence - one row):
| n | total | OUTPUT |
|---|---|---|
| 3 | 6 | 6 |
Algorithm B reaches the same answer in a single row - no loop required.
Both algorithms are correct - same inputs, same output. They differ in important ways:
| Algorithm A (Loop) | Algorithm B (Formula) | |
|---|---|---|
| Trace rows | Grows as n increases | Always one row |
| Uses a loop | Yes | No |
| Readability | Clear logic, easier for beginners | Compact, but requires formula knowledge |
| Works for any n | Yes | Yes (if formula is applied correctly) |
Neither algorithm is always "better" - the right choice depends on context. Recognising that alternatives exist is the starting point for thinking like a computer scientist.
Key Takeaways
- More than one algorithm can solve the same problem - having the same inputs and outputs does not mean using the same steps.
- Two algorithms solve the same problem if they accept the same inputs and always produce the same correct output.
- Different algorithms can differ in the number of steps taken, the structures used, and how well they scale to larger inputs.
- A trace table can be used to verify that two different algorithms produce the same result for a given input.
- Choosing between correct algorithms requires considering simplicity, the number of steps, and the context in which they will be used.