Docsity

Counting Iterations and Combinations in Nested Loops and Sets, Slides of Discrete Mathematics

Partial preview of the text

Download Counting Iterations and Combinations in Nested Loops and Sets and more Slides Discrete Mathematics in PDF only on Docsity!

1

Counting Techniques:

r-combinations with

repetition allowed,

Binomial theorem

2

Number of iterations of a nested loop

(First Situation)

 Consider the following nested loop:

for i:=1 to n

for j:=1 to i-

for k:=1 to j-

[ Statements]

next k

next j

next i

 Question: How many times the statements in the innermost

loop will be executed?

 Solution: Each iteration corresponds to

a triple of integers (i, j, k) where i > j > k.

The set of all this kind of triples corresponds to

all 3 -combinations of {1, …, n}.

Thus, the total number of iterations is C(n,3).

Number of iterations of a nested loop

(Second Situation)

Each triple corresponds to a string of crosses and vertical bars.

  • Numbers 1, 2, …, n are considered as categories ;
  • n-1 vertical bars separate the categories;
  • 3 crosses indicate

how many items from each category are chosen.

Examples when n=5:

Category

Triple

× | | × | × | (5, 3, 2)

| ×× | × | | (4, 4, 3)

| | | × | ×× (2, 1, 1)

5

Number of iterations of a nested loop

(Second Situation)

  • Each triple corresponds to

a string of n-1 vertical bars and 3 crosses.

The length of any string is (n-1)+3 = n+.

The number of distinct positions

for the 3 crosses in a string is C(n+2, 3).

Thus, the number of distinct triples is C(n+2, 3).

Generalizing,

if the number of nested loops is r

then the number of iterations is C(n-1+r, r).

Which formula to use?

  • We discussed four different ways

of choosing r elements from n.

  • The summary of formulas

used in the four situations:

Order matters Order does not

matter

Repetition allowed

Repetition not

allowed

n

r

P(n,r)

C(n-1+r, r)

C(n,r)

8

Useful formulas for special cases

  • C(n,n-r) = C(n,r).

Proof :

  • C(n,n)=
  • C(n,n-1) = C(n,1) = n
  • C(n,n-2) = C(n,2) = n(n-1) / 2

( , ) C n r

n r r

n

n r n n r

n

C n n r =

10

Binomial Theorem

Proof(cont.): For each k=0,1,…, n ,

the product a

n-k

b

k

occurs as a term in the sum

the same number of times

as the number of ways to choose k positions for b’s.

But this number is C(n,k).

Thus, the coefficient of a

n-k

b

k is C(n,k). ■

Examples: (a+b)

2

= a

2

+C(2,1)∙ab+b

2

= a

2

+2∙ab+b

2

(a+b)

3

= a

3

+C(3,1)∙a

2

b+C(3,2)∙ab

2

+b

3

= a

3

+3∙a

2

b+3∙ab

2

+b

3

11

Using the Binomial Theorem

  • Question: Which number is larger:

4,

or 800?

  • Solution: By the binomial theorem,

4,

4,

4000

+ C(4000, 1)∙

3999

+ other positive terms

= 1 + 4000∙1∙.2 + other positive terms

= 1 + 800 + other positive terms > 800