Algorithms Worksheet 1 Analysis and Design of
Algorithms Worksheet 1 Analysis and Design of
Unit 12 Algorithms
(b) What is the time complexity of an algorithm that has 5n2 + 10n + 2 steps, expressed
in the Big-O notation?
O(5n^2)
(b) for i = 0 to n
for j = 0 to n
k = n*2 + i * j
next j
next i
assignment statements = n + n = n2
Big O time complextity =O(n2)
(c) for i = 1 to n
1
Worksheet 1 Analysis and algorithms
Unit 12 Algorithms
x = 5 + i * i
next i
for j = 1 to n
y = 10 – j
next j
assignment statements = n + n = n2
Big O time complextity =O(262)
Task 2
1. (a) How many different permutations would have to be checked using a “brute force”
method, on average, to crack a password, if it is known to be 4 uppercase alphabetic
characters?
264
(b) How many would have to be checked, in the worst case scenario?
(264) / 2
2. Look at the following graphs. A graph which has an edge connecting every vertex is said to
be “complete”.
(b) A computer game has 5 doors which have to be opened in a particular sequence in
order to progress to the next step. In how many different orders can the doors be
opened?
2
Worksheet 1 Analysis and algorithms
Unit 12 Algorithms
5^n
(c) What is the order of complexity of the problem if there are n doors?
(d) Suppose there were 7 doors. How many doors would need to be opened, on average,
to find the correct door using a “Brute Force” method?
7^n
3
Worksheet 1 Analysis and algorithms
Unit 12 Algorithms
3. In the Fibonacci sequence 0, 1, 1, 2, 3, 5, 8 … , each number after the first two is the sum
of the two previous numbers.
What will be the next two numbers in the sequence?
Here are two subroutines written in Python each designed to find the first n numbers in the
Fibonacci series.
Subroutine 1: (a recursive routine)
def fibonacci(n):
if n == 0:
return 0
if n == 1:
return 1
return fibonacci(n-1) + fibonacci(n-2)
n = 20
n = 25
n = 30
n = 35
n = 40
(estimate)
N = 100
(estimate)
Which of O(n) O(n2) O(2n) O (log n) is the approximate time complexity of:
(a) the recursive subroutine?
4
Worksheet 1 Analysis and algorithms
Unit 12 Algorithms
(a) The aim of the Big-O notation is to give a rough idea of how time and/or memory
requirements will grow as the problem gets bigger
(b) The statement “The worst case run-time complexity of algorithm A is O(n2)” means
that “Algorithm A takes at most c x n2 steps (where c is a constant) to solve a problem
of size n (for large n)”
(c) Problems of complexity O(1) have only one statement, however large the problem
(d) A problem with complexity O(100n) is of a different order of magnitude from one of
complexity O(n)
(g) Some problems may be O(n) for small values of n but O(n2) for large values of n
(h) “Divide and conquer” algorithms typically have time complexity O(log n) and are
very efficient