a)

 

function fn = fibonacci(n)
if n < 3
    fn = 1;
else
    fn = fibonacci (n-2)+fibonacci (n-1);
end

 

b)

 

function fibStore(n,filename)
fib = fibonacci(n);
fhandle = fopen(filename,'w');
for element = fib
    fprintf(fhandle,'%d\n',element);
end
end
 
function list = fibonacci(n)
list = ones(1,n);
if n > 2
    a = fibonacci(n-1);
    list(1:n-1) = a;
    list(n) = a(end-1) + a(end);
end
end

 

c)

 

function res = fact(n)
if n > 1
    res = n*fact(n-1);
else
    res = 1;
end
end

 

d)

 

function r = des2bin (n)
if n == 0
    r = '0';
elseif n == 1
    r = '1';
else
    rest = rem (n ,2) ;
    if rest == 0
        r = [ des2bin ( n/2 ) '0'];
    else
        r = [ des2bin ( (n -1) /2 ) '1'];
    end
end
end

 

e)

 

function tower_of_hanoi (n, source , dest , temp )
if n > 0
    tower_of_hanoi (n -1, source , temp , dest );
    fprintf ('Flytt fra %i til %i\n', source , dest );
    tower_of_hanoi (n -1, temp , dest , source );
end
end

 

f)

 

function  result = recSine(x,tol)
if x > tol
x = recSine(x/3,tol);
result = 3*x-4*x^3;
else
    result = 3*(x/3)-4*(x/3)^3;
end
end

 

g)

 

function  result = recMult(n,tol)
if (1+1/n^2) < 1+ tol
    result =  1;
else
    result = (1+1/n^2)*recMult(n+1,tol);
    disp(result)
end
end

 

 

  • No labels