Last active
June 3, 2020 11:45
-
-
Save juanelopezm/9941b6502b17315d04154d304e38effc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -module(recursion). | |
| -export([fac/1,fib/1,pieces/1,pieces_n_dimentions/2]). | |
| %Factorial | |
| fac(0) -> | |
| 1; | |
| fac(N) when N>0 -> | |
| fac(N-1)*N; | |
| fac(_) -> | |
| 'error'. | |
| %Fibonacci numbers | |
| %The Fibonacci sequence is given by 0, 1, 1, 2, 3, 5, … where subsequent values are given by adding the two previous values in the sequence. | |
| %Give a recursive definition of the function fib/1 computing the Fibonacci numbers, and give a step-by-step evaluation of fib(4). | |
| fib(0) -> | |
| 0; | |
| fib(1) -> | |
| 1; | |
| fib(N) when N>1 -> | |
| fib(N-1)+fib(N-2); | |
| fib(_) -> | |
| "Error!!!". | |
| %Evaluate fin(4): | |
| %fib(4). | |
| %fib(3) + fib(2) | |
| %(fib(2) + fib(1)) + (fib(1) + fib(0)). | |
| %(fib(1) + fib(0)) + 1) + (1 + 0). | |
| %(1 + 0) + 1) + (1). | |
| %(1 + 1) + 1. | |
| %2 + 1. | |
| %3. | |
| %How many pieces? | |
| %Define a function pieces so that pieces(N) tells you the maximum number of pieces into which you can cut a piece of paper with N straight line cuts. | |
| %You can see an illustration of this problem at the top of this step. | |
| %If you’d like to take this problem further, think about the 3-dimensional case. Into how many pieces can you cut a wooden block with N saw cuts? | |
| pieces(0) -> | |
| 0; | |
| pieces(Cuts) when Cuts>1 -> | |
| pieces(Cuts-1)+Cuts; | |
| pieces(_) -> | |
| "Error". | |
| pieces_n_dimentions(_,0) -> | |
| 0; | |
| pieces_n_dimentions(0,_) -> | |
| 1; | |
| pieces_n_dimentions(1,_) -> | |
| 2; | |
| pieces_n_dimentions(Cuts, Dimentions) when Cuts > 1 -> | |
| pieces_n_dimentions(Cuts - 1, Dimentions - 1) + pieces_n_dimentions(Cuts - 1, Dimentions); | |
| pieces_n_dimentions(_,_) -> | |
| "Error". |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment