Algorithms & Flowcharts — Worked Examples

8. Classic Math Algorithms

Classic Math Algorithms

These four algorithms show up again and again in programming courses and interviews. Each uses a loop with a clear changing state, so trace tables are the best way to understand them.

Example (a): Check if a number is prime

Problem

A prime number (2, 3, 5, 7, 11, ...) has exactly two divisors: 1 and itself. Decide whether N is prime by testing every possible divisor from 2 up to N-1: if any divides N evenly, N is not prime.

Start INPUT N isPrime = true , i = 2 is i <= N-1 ? No (exit) Yes is N % i == 0 ? Yes isPrime = false No i = i + 1 loop back OUTPUT isPrime End

Reading the chart: the inner diamond asks "does i divide N?". If Yes we set isPrime = false and leave the loop; if No we add 1 to i and check the next divisor. When i passes N-1 with isPrime still true, N is prime.

Pseudocode

INPUT N
SET isPrime = true
SET i = 2
WHILE i <= N - 1
    IF N % i == 0
        SET isPrime = false
    SET i = i + 1
IF isPrime == true
    OUTPUT "prime"
ELSE
    OUTPUT "not prime"

Trace table

Sample input: N = 7. We test i = 2, 3, 4, 5, 6. None divide 7 evenly, so the remainder (N % i) is never 0 and isPrime stays true.

Iterationii <= 6 ?7 % idivides evenly?isPrime
start2---true
12Yes1Notrue
23Yes1Notrue
34Yes3Notrue
45Yes2Notrue
56Yes1Notrue
exit7No--true

isPrime is still true, so 7 is prime. (If we had tried N = 9, then at i = 3 the remainder 9 % 3 would be 0, isPrime would flip to false, and 9 would be "not prime".)

In Python

N = 7
is_prime = True
i = 2
while i <= N - 1:
    if N % i == 0:
        is_prime = False
    i = i + 1
if is_prime and N >= 2:
    print("prime")
else:
    print("not prime")

# Output:
# prime

Example (b): Greatest common divisor (Euclid's algorithm)

Problem

The greatest common divisor (GCD) of two numbers is the largest number that divides both. Euclid's algorithm finds it fast: keep replacing the pair (a, b) with (b, a % b) until b becomes 0; then a is the answer.

Start INPUT a , b is b != 0 ? Yes temp = a % b a = b , b = temp loop back No OUTPUT a (the GCD) End

Pseudocode

INPUT a, b
WHILE b != 0
    SET temp = a % b
    SET a = b
    SET b = temp
OUTPUT a

Trace table

Sample input: a = 48, b = 36. Watch both a and b each step.

Iterationa (before)b (before)b != 0 ?temp = a % ba after (= old b)b after (= temp)
14836Yes48 % 36 = 123612
23612Yes36 % 12 = 0120
exit120No-120

When b reaches 0 the loop stops and a = 12 is the GCD of 48 and 36.

In Python

a = 48
b = 36
while b != 0:
    temp = a % b
    a = b
    b = temp
print(a)

# Output:
# 12

Example (c): First N Fibonacci numbers

Problem

The Fibonacci sequence starts 0, 1 and every later number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, ... Print the first N of them.

Start INPUT N prev = 0 , curr = 1 , i = 1 is i <= N ? Yes OUTPUT prev next = prev + curr prev = curr , curr = next , i = i+1 loop back No OUTPUT done End

Pseudocode

INPUT N
SET prev = 0
SET curr = 1
FOR i FROM 1 TO N
    OUTPUT prev
    SET next = prev + curr
    SET prev = curr
    SET curr = next

Trace table

Sample input: N = 7. The printed number each pass is the prev value.

Iteration (i)prev (printed)currnext = prev + currprev aftercurr after
start01-01
1010 + 1 = 111
2111 + 1 = 212
3121 + 2 = 323
4232 + 3 = 535
5353 + 5 = 858
6585 + 8 = 13813
78138 + 13 = 211321

Numbers printed: 0 1 1 2 3 5 8.

In Python

N = 7
prev = 0
curr = 1
for i in range(N):
    print(prev, end=" ")
    next_num = prev + curr
    prev = curr
    curr = next_num
print()

# Output:
# 0 1 1 2 3 5 8

Example (d): Compute x raised to the power n with a loop

Problem

Work out x to the power n (x multiplied by itself n times) without using a built-in power operator. For example 2 to the power 5 is 2 x 2 x 2 x 2 x 2 = 32.

Start INPUT x , n result = 1 , i = 1 is i <= n ? Yes result = result * x i = i + 1 loop back No OUTPUT result End

Pseudocode

INPUT x, n
SET result = 1
SET i = 1
WHILE i <= n
    SET result = result * x
    SET i = i + 1
OUTPUT result

Trace table

Sample input: x = 2, n = 5. The accumulator result starts at 1 and gets multiplied by x each pass.

Iterationii <= 5 ?result = result * 2result afteri after
start1--11
11Yes1 * 222
22Yes2 * 243
33Yes4 * 284
44Yes8 * 2165
55Yes16 * 2326
exit6No-326

2 to the power 5 = 32.

In Python

x = 2
n = 5
result = 1
i = 1
while i <= n:
    result = result * x
    i = i + 1
print(result)

# Output:
# 32