{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

lecture5-6

lecture5-6 - CS106lecture5,6notes Recursivefunctions ....

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
CS 106 lecture 5, 6 notes Recursive functions A recursive function is a function that calls itself. These arise naturally from many mathematical definitions, e.g. factorial: n! = n(n‐1)(n‐1) … 1 = n(n‐1)! Where 0! = 1 An iterative solution would be: function [ fac ] = faci( n ) % faci computes n! iteratively % works for 0 because loop does not execute fac = 1; for i = 1:n fac = fac*i; end end A recursive solution on the other hand is: function [ fac ] = facr( n ) % facr computes n! recursively % if n == 0 % the escape fro the iteration fac = 1; else fac = n*facr(n-1); end end A recursive function needs some step which reduces the problem and code that causes the recursion to come to a stop. Recursion is often a quick way to write a function, especially if it is tied to a mathematical definition, but sometimes it is simply the easiest way to break down a problem though perhaps not the most efficient. A recursive function that pushes the limits of computers quite quickly is the harmless looking Ackermann function n + 1 if m = 0 A(m,n) = A(m‐1,1) if m > 0 and n = 0 A(m‐1,A(m,n‐1)) if m > 0 and n > 0
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Try writing it as a recursive function. Triangles In Project Euler (projecteuler.net) there is a problem where you are given 1000 triangles in a file, as 1000 lines with three pairs of points per line.
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 6

lecture5-6 - CS106lecture5,6notes Recursivefunctions ....

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon bookmark
Ask a homework question - tutors are online