Chapter 5 - Counting
Chapter 5 - Counting
2
Task 1: choose one
Task 2: choose one
4
Product rule
THE PRODUCT RULE
A• •1
B• •2
C• •3
•4
•5
Example – counting passwords
• Each user on a computer system has a
password, which has properties:
• six to eight characters long
• character is an uppercase letter or a digit
• contain at least one digit
• How many possible passwords are there?
• Result = (366 – 266) + (367-267) + (368 – 268)
all all invalid cases = cases without digit
6 characters ******
Exercises
1/ If there are 5 multiple-choice questions on
an exam, each having four possible answers,
how many different sequences of answers are
there?
2/ In how many ways can a teacher seat 5
girls and 3 boys in a row seats if a boy must be
seated in the first and a girl in the last seat?
Exercises
1/ How many positive divisors does 120 have?
2/ A = {1, 2, 3, 4, 5, 6}
a. How many subsets of A can be
constructed?
b. How many subsets of A that contain
1?
c. How many subsets neither contain 3
nor 4?
How many integers between 10
and 30 inclusive are divisible by
3 or 7?
The principle of Inclusion-
exclusion
•a
•f
A
•b •d B
•e
•c
27 ways 26 ways
25 ways
• Result = 27 + 26 - 25
Advanced counting techniques
• 3 disks → 7 steps
Tower of Hanoi problem
• n = 1 disk H1 = 1 step
• n = 2 disks:
Peg1 → Peg3
Peg1 → Peg2
Peg2 Peg3
H2 = 3 steps
• n = 3 disks H3 = 7 steps
• n disks Hn = ? // number of steps for n disks
How many steps
Tower of Hanoi problem -
3 disks: H3 = 7 steps
• Initial conditions:
• H1=1
• a1=2, a2=3
Recurrence Relations
• Example: Determine whether {an} = 3n is a solution
of the recurrence relation
an= 2an-1 – an-2, n ≥ 2?
• an = 3n an-1 = 3(n-1) and an-2 = 3(n-2)
• The right-hand side = 2an-1 – an-2 = 2.3(n-1) – 3(n-2)
• The right-hand side = 3n = an
• Left-hand side = Right-hand side
• an is a solution of the recurrence relation
Divide-and-Conquer Algorithms
and recurrence Relations
return 0
else
m= (i+j)/2
if x= am
return m
else if x< am
bsearch(x, i, m-1) need f(n/2)
else comparisons
bsearch(x, m+1, j)
f(n) = f(n/2) +2
Recurrence Relations for Finding Maximum of a
sequence
procedure findmax(i,j: integer ,ai,a2+1,…,aj: need f(n)
comparisons
integers)
if i=j
return (ai) f(n) = 2f(n/2) +1
else
m:= (i+j)/2
max1:= findmax (i,m,ai,ai+1,…,am) need f(n/2)
comparisons
need f(n/2)
max2:= findmax (m+1,j,am+1,am+2,…,aj) comparisons
if max1 > max2
return max1
else
return max2
Theorem. [ … ]
f(n)= af(n/b) + c ➔
a=1 c=2
b=2
Ex.
f(n) = f(n/2) + 2
➔ f(n) is O(logn)
?
O(logn) time complexity
Theorem. [ … ]
f(n)= af(n/b) + c ➔
f(n) = 2f(n/2) + n
Total number of
points in the strip
does not exceed n
and there are at
most 8 points,
including p, can lie
in or on the 2dxd
rectangle.