(1) * Givent an integer N, write a program that sums all odd natural numbers les
ID: 3209812 • Letter: #
Question
(1) * Givent an integer N, write a program that sums all odd natural numbers less than or equal to N, i.e. computes S = 1+3+5+...+ (m – 2) + m, where m = N if N is odd, and m = N — 1 if N is even. Write two implementations: (a) Use an appropriate for- or while-loop. Filename: _la (b) Solve this problem by recursively calling an appropriately defined function, avoid the use of loops. Filename: _1b (c) Run your program for different values of N, and measure the runtime (import time): N E {10, 100, 1000, 10000}. Which implementation is faster? Each code should contain a function main (N), which takes the integer N as an argument, and prints the result when called.Explanation / Answer
Part (a) of the question:
clc
clear
N = input('Enter N: ');
s = 0;
for i=1:2:N
s = s + i;
end
fprintf("The sum is: "+s);
------X----X-----
Part (b) of the question:
Script ( run this file )
clc
clear
s = 0;
N = input('Enter N: ');
s = RecurseOddEven(N,s);
fprintf("The sum is: "+s);
---XX--
Function (call this file from the script)
function [s] = RecurseOddEven(N,s)
if rem(N,2) == 0
N = N - 1;
end
if (N-2) >= -1
s = s + N + RecurseOddEven(N-2,s);
end
end
----X----X----
Part (c).
**Script**
clc
clear
tic
for i = 1:4
s = 0;
N = 10^i;
s = RecurseOddEven(N,s);
fprintf("The sum is: "+s);
end
toc
**FUNCTION FILE**
function [s] = RecurseOddEven(N,s)
if rem(N,2) == 0
N = N - 1;
end
if (N-2) >= -1
s = s + N + RecurseOddEven(N-2,s);
end
end
***With LOOPS***
clc
clear
tic
for j = 1:4
N = 10^j;
s = 0;
for i=1:2:N
s = s + i;
end
fprintf("The sum is: "+s);
end
toc
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.