

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
fibonacci promblem set for student
Typology: Exercises
1 / 3
This page cannot be seen from the preview
Don't miss anything!


Problem 1 - Count the Number of Recursive Calls
function [result, count] = fibonacci_count(n) % Counted recursive Fibonacci if n == 0 || n == 1 result = n; count = 1; % this call else [r1, c1] = fibonacci_count(n-1); [r2, c2] = fibonacci_count(n-2); result = r1 + r2; count = c1 + c2 + 1; % +1 for this call end end
%% Command window test n = 5; [fib, calls] = fibonacci_count(n); fprintf('Fibonacci(%d) = %d, recursive calls = %d\n', n, fib, calls);
Problem 2 - Compare Recursive vs Iterative Timing
function fib = fibonacci_basic(n) if ~isscalar(n) || n < 0 || n ~= fix(n) error('n must be a non-negative integer'); end fib = zeros(1,n+1); fib(1) = 0; if n >= 1, fib(2) = 1; end for k = 3:n+ fib(k) = fib(k-1) + fib(k-2); end fib = fib(end); % return F(n) only end
Create the script timing_compare.m:
%% timing_compare.m - script n = 30; tic, r = fibonacci(n); recTime = toc; tic, ri = fibonacci_basic(n); iterTime = toc; fprintf('Recursive: %.6f s\n', recTime); fprintf('Iterative: %.6f s\n', iterTime);
Problem 3 - Plot Number of Recursive Calls vs n
%% plot_recursive_calls.m N = 1:20; % range of n values calls = zeros(size(N)); for k = 1:numel(N) [~, calls(k)] = fibonacci_count(N(k)); end figure; plot(N, calls, 'ro-', 'LineWidth', 1.5); xlabel('n'); ylabel('Recursive Calls'); title('Growth of Recursive Calls in Fibonacci(n)'); grid on;
Problem 4 - Fibonacci Modulo m
function result = fibonacci_mod(n, m) if n == 0 || n == 1 result = n; else result = mod(fibonacci_mod(n-1, m) + fibonacci_mod(n-2, m), m); end end
%% Command window test n = 10; m = 7; fprintf('Fibonacci(%d) mod %d = %d\n', n, m, fibonacci_mod(n, m));
Problem 5 - Detect If a Number Is Fibonacci
function tf = is_fibonacci(num) tf = is_perfect_square(5num^2 + 4) || is_perfect_square(5num^2 - 4); end
function tf = is_perfect_square(x) s = sqrt(x); tf = s == floor(s); end