a)
Code Block | ||
---|---|---|
| ||
function fn = fibonacci(n) |
if n < |
3
fn =
1
;
else
fn = fibonacci 3 fn = 1; else fn = fibonacci (n-2)+fibonacci (n-1); |
end |
b)
Code Block | ||
---|---|---|
| ||
function fibStore(n,filename) |
fib = fibonacci(n); |
fhandle = fopen(filename,'w'); |
for element = |
fib fprintf(fhandle,'%d\n',element); |
end |
end
end function list = fibonacci(n) |
list = ones(1,n); |
if n > |
2
a = 2 a = fibonacci(n-1); |
fnlist(1:n-1) = a; |
fnlist(n) = a(end-1) + a(end); |
end |
end |
c)
Code Block | ||
---|---|---|
| ||
function |
res = fact(n) |
if n |
2
ret = > 1 res = n*fact(n-1); |
else
ret =
2
;
end
else res = 1; end end |
d)
Code Block | ||
---|---|---|
| ||
function r = des2bin (n) |
if n == |
0
r =
0 r = '0'; |
elseif n == |
1
r =
1 r = '1'; |
else
rest = rem (n else rest = rem (n ,2) |
if
rest ; if rest == |
0
r = [ des2bin ( 0 r = [ des2bin ( n/2 ) '0']; |
else
r = [ des2bin ( (n else r = [ des2bin ( (n -1) /2 ) '1']; |
end
end
end end end |
e)
Code Block | ||
---|---|---|
| ||
function tower_of_hanoi (n, source , dest , temp ) |
if n > |
0
0 tower_of_hanoi (n -1, source , temp , dest ); |
fprintf fprintf ('Flytt fra %i til %i\n', source , dest ); |
tower_of_hanoi (n -1, temp , dest , source ); |
end |
end |
f)
function result =
Code Block | ||
---|---|---|
| ||
function result = recSine(x,tol) |
if x > tol |
x = recSine(x/3,tol); |
result = 3*x-4* |
3
x^3; |
else
result =
else result = 3*(x/3)-4*(x/3) |
3
^3; |
end |
end |
g)
function result =
Code Block | ||
---|---|---|
| ||
function result = recMult(n,tol) |
if (1+1/ |
2
n^2) < 1+ |
result =
1
;
else
result = tol result = 1; else result = (1+1/ |
2
n^2)*recMult(n+1,tol); |
disp(result) end end |
end
end