DEL 1
a)
Code Block |
---|
function res = isPalindrome ( str ) n = size (str , 2); res = true ; for i =1: n if str (i) ~= str (n+1-i) res = false ; break end end end |
b)
Code Block |
---|
function res = sequenceFinder (sequence,start,stop ) len = 0; index = 0; for i = 1:length(sequence)-length(stop) if (length(start) <= length(sequence(i:end))) && strcmp(start,sequence(i:i+length(start)-1)) indexS = i; elseif (length(stop) <= length(sequence(i:end))) && strcmp(stop,sequence(i:i+length(start)-1)) indexE = i; if len < indexE -indexS len = indexE -indexS; index = indexS; end end end res = sequence(index:index+len+length(stop)-1); end |
Eventuelt kan den lages litt enklere ved hjelp av matlabs strfind() funksjon.
DEL 2
a)
Code Block |
---|
function a = isDevisable(a,b) a = ~mod(a,b); end |
b)
Code Block |
---|
function res = prime(a) res = 1; for b = 2:a-1 if isDevisable(a,b) res = 0; break; end end end function a = isDevisable(a,b) a = ~mod(a,b); end |
c)
Code Block |
---|
function res = prime(a) res = 1; if isDevisable(a,2) res = 0; return; end for b = 1:2:ceil(sqrt(a)) if isDevisable(a,b) res = 0; break; end end end |
d) og e)
Code Block |
---|
les = fopen('prim.txt','r'); if les ==-1 break; end A = fscanf(les,'%f'); if isempty(A) % Om filen er tom skriver vi '2' inn i den. x = 2; A(1)= 2; skriv = fopen('prim.txt','w'); fprintf(skriv, '%20f\r\n',x); else % Ellers skriver vi inn alt, skriv = fopen('prim.txt','w'); x = A(end); fprintf(skriv, '%20f\r\n',A); end while (length(A) < 1500200) x = x + 1; i=1; prime = 1; while sqrt(x)>= A(i) if x/A(i) == floor(x/A(i)) prime = 0; break; end i = i+1; end if prime % Legger det til i listen, og til filen. fprintf(skriv, '%20f\r\n',x); A = [A; x]; end end fclose('all'); |