Docsity

Lecture Notes on Recursive Algorithm | CS 3653, Study notes of Computer Science

Toggle sidebar
bg1
CS 3653 Fall 2002 Lecture 10-1 T. Menhaj
Lecture 10
Algorithms (cont’d)
Recursive Algorithm
Example: n! =
()
0
n
i
ni
=
−
∏= n (n-1)!
Original problem: Find n!
Decompose it into simpler subproblems. Find (n-1)!,
(n-2)!,...,0!=1. The solutions of these simplier problems
are combined to solve the original one.
Algorithm:
Input n
function N=factorial(n)
if n<=0 then N=1
else N=n*factorial(n-1)
end if
endfunction
Definition: A recursive function is a function that invokes
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Lecture Notes on Recursive Algorithm | CS 3653 and more Study notes Computer Science in PDF only on Docsity!

Lecture 10 Algorithms (cont’d) Recursive Algorithm

Example: n! = 0 (^ )

n

∏ i = n^ − i = n (n-1)!

Original problem: Find n!

Decompose it into simpler subproblems. Find (n-1)!, (n-2)!,...,0!=1. The solutions of these simplier problems are combined to solve the original one.

Algorithm:

Input n function N=factorial(n) if n<=0 then N= else N=n*factorial(n-1) end if endfunction

Definition: A recursive function is a function that invokes

itself. A recursive algorithm is an algorithm that contains a recursive function.

Note: there must be some situations in which the recursive algorithm does not invoke itself. Bases Cases: The values for which the algorithm does not call itself.

Recursive algorithm for gcd problem

Input a, b ∈^ ]+^ , both non-zero

function N=gcd_rec(A,B) a=max(A,B), b=min(A,B) if b=0 , then N=a else r=a mod b ≡^ a^ −^ ^ ab ⋅ b N=gcd_rec(b,r) endif endfunction

Alternatively: if A>=B, then a=A, b=B else a=B, b=A endif

Algorithm for x(k):

Function x=diffeq(a,b) If (a==0 and b==0), then x=0 , return Endif x=0.5a+0.2b b=a a=x x=diffeq(a,b) endfunction

Algorithmic language: Syntax and Semantics

1.1 Assignment, "=" LHS=RHS

LHS stands for Left Hand Side RHS stands for Right Hand Side

LHS is a variable, RHS is a mathematical expresssion.

Examples: a= a=2sin(t)-4cos(t) a=2*a

1.2 Selection

If P1 then q1, q2,...,qn endif

This is the same as: repeat until p ... endrepeat

I/O information:

Input (a,"x:") or Read (a,"x:") Output (a,"x:") or Display (a,"x:") or Print (a,"x:") or Write (a,"x:")

Example : Write an algorithm to calculate ex. Fact: 2 3 0

1 1 1 1 ! 2 6

x k e = (^) k ∑= (^) k x = + x + x + x +" function y=exp(x) n= s= fn= if x<0 then t=-x endif y=x; repeat until t<10^- s=s+y, n=n+ fn=nfn t=1/fnx^n y=t if t<0, then t=-t endif endrepeat endfunction

  • Number of additions:
  • Number of multiplications:

What if we rewrite:

y=a[0]+a[1]x+a2 as y=a[0]+x(a[1]+a[2]x)

Number of additions: 2 Number of multiplications: 2

So this new algorithm is more efficient.

Code:

function y=poly1(x,a[1 to n],n) y=a[0] s= for i=1 to n s=sx y=y+a[i]s endfor endfunction