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 fn = fibonacci(n) fn = ones(1,n); if n > 2 a = fibonacci(n-1); fn(1:n-1) = a; fn(n) = a(end-1) + a(end); end end
c)
function ret = fact(n) if n > 2 ret = n*fact(n-1); else ret = 2; 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 kallepaaSinus() tol = 0.01; x = 0.5; ans = recSine(x,tol) end function verdi = recSine(x,tol) if x > tol x = recSine(x/3,tol); verdi = 3*x-4*x^3; else verdi = 3*(x/3)-4*(x/3)^3; end end
g)
function kallepaaMult() tol = 0.01; ans = recMult(1,tol) end function verdi = recMult(n,tol) if (1+1/n^2) < 1+ tol verdi = 1; else verdi = (1+1/n^2)*recMult(n+1,tol); display(verdi) end end