% Section 3 Solutions % -------------------- % #1 Nested Branching x = input('input x: '); if (x < 0) fx = x^2; else if (x < 1) % no need to check that x is greater than or equal % to 0. If x were less than 0 the program would % have entered the previous "if" block and then % move right to the "end" of this if-elseif-... % block fx = x; else % x >= 1 if (x < 9) fx = 2*x; else % x >=9 fx = sqrt(x); end end end fprintf('Result: %f\n',fx); % -------------------- % #2 Basic Fibonacci: Print F(1), F(2), ..., F(n) % n= input('Input n: '); value1= 1; value2= 1; fib= 0; if (n >= 1) if (n == 1) fprintf('%d ', value1); elseif (n == 2) fprintf('%d %d ', value1, value2); else for i=3:n fib= value1 + value2; value1= value2; value2= fib; fprintf('%d ', value2); end end disp(' '); else disp('Must input number > 0'); end % -------------------- % #3 Advanced Fibonacci (consecutive--not nested--loops) % Print all integers from F(n) to F(n+1), inclusive % n= input('Input n: '); value1= 1; value2= 1; if (n >= 1) if (n == 1) fprintf('%d ', value1) elseif (n==2) fprintf('%d %d ', value2, value1+value2) else for i=3:n+1 fib = value1 + value2; value1 = value2; value2 = fib; % At this point, value2 is F(i) and value 1 is F(i-1) end for i=value1:value2 fprintf('%d ', i); end end disp(' '); else disp('Must input number > 0'); end % -------------------- % #4 Factors of n n= input('Input n: '); if (n >= 1) for i=2:n-1 if (mod(n,i) == 0) fprintf('%d ', i); end end disp(' '); else disp('Must input number > 0'); end % ----------------------------- % Challenge: Prime Factors of n % n= input('Input n: '); if (n >= 1) for i=2:n-1 if (mod(n,i) == 0) j= 2; while (mod(i,j) ~= 0 && j <= i) j = j + 1; end if (j == i) fprintf('%d ', i); end end end disp(' '); else disp('Must input number > 0'); end