Lecture 13-14
Lecture 13-14
Algorithms,
Inference Rules
Discrete Structure
MUHAMMAD UMAR NASIR
LECTURER FCS RIPHAH INTERNATIONAL UNIVERSITY LAHORE
Recursive Algorithm
factorial(4)
4≠0 4.6=24
4.factorial(3)
3≠0 3.2=6
3.factorial(2)
2≠0 2.1=2
2.factorial(1) 1.1=1
1≠0
1.factorial(0)
0=0 so return 1
A Recursive Algorithm for
Computing an
procedure power(a: nonzero real number, n: nonnegative
integer)
if n = 0 then return 1
else return a · power(a, n − 1)
{output is an}
A Recursive Algorithm for
Computing an
Calculate 24 using recursive algorithm for computing an
power(2,4)
4≠0 2.8=16
2.power(2,3)
3≠0 2.4=8
2.power(2,2)
2≠0 2.2=4
2.power(2,1) 2.1=2
1≠0
2.power(2,0)
0=0 so return 1
GCD:
gcd(5,8)
gcd(8 mod 5, 5)
= gcd(3,5) 1
=gcd(2,3) 1
gcd(2 mod 1, 1)
=gcd(0,1)
So gcd of 5 and 8 is 1
A Recursive Algorithm for
Computing gcd(a, b)
Find GCD of 4 and 12 using recursive algorithm
gcd(4,12)
So GCD of 4 and 12 is 4
A Recursive Algorithm for
Computing gcd(a, b)
Find GCD of 8 and 12 using recursive algorithm
gcd(8,12)
gcd(12 mod 8,
8)
4
= gcd(4,8)
So GCd of 8 and 12 is 4
Fibonacci Numbers:
fibonacci(4)
1 fibonacci(3) 1 fibonacci(2)
1 0
fibonacci(1) fibonacci(0)
Series 0 1 1 2 3
Recursive Linear Search
Algorithm:
procedure search(i, j, x: i, j, x integers, 1 ≤ i ≤ j ≤ n)
if ai = x then
return i
else if i = j then
return 0
else
return search(i + 1, j, x)
{output is the location of x in a1, a2, . . . , an if it appears;
otherwise it is 0}
Recursive Linear Search
Algorithm:
Search 7 from the list 4 , 6 , 2 , 7 , 1 , 3 using Recursive Linear search Algorithm
Search(1,6, 4,6,2,7,1,3
7)
Search(2,6,7) 4,6,2,7,1,3
Search(3,6,7) 4,6,2,7,1,3
Search(4,6,7) 4,6,2,7,1,3
a4=7 so Element
found at
return 4 location 4
Recursive Linear Search
Algorithm:
Search 5 from the list 4 , 6 , 2 , 7 , 1 , 3 using Recursive Linear search Algorithm
Search(1,6,5) 4,6,2,7,1,3
Search(2,6,5) 4,6,2,7,1,3
Search(3,6,5) 4,6,2,7,1,3
Search(4,6,5) 4,6,2,7,1,3
Search(5,6,5) 4,6,2,7,1,3
4,6,2,7,1,3 Search(6,6,5)
m=3
a3≠7 and
Search(4,6,7) 2,5,6,7,8,11
m=5
a5≠7 and
Search(4,4,7) 2,5,6,7,8,11
a4=7 So Element
fount at
return 4 location 4
Rules of Inference:
∴ p ∨q
p
∴ p