The function WeirdSum takes as input a positive integer n, and returns the sum o
ID: 3716272 • Letter: T
Question
The function WeirdSum takes as input a positive integer n, and returns the sum of all numbers between 1 and n?1 that are either divisible by 3 or divisible by 4, but not both.
For instance, WeirdSum(5) = 7, WeirdSum(8) = 13, and WeirdSum(13) = 30
.
(a) Write a matlab function WeirdSumForLoop.m that uses a for loop to calculate WeirdSum(n) for any positive integer n.
(b) Write a matlab function WeirdSumNoLoop.m that calculates WeirdSum(n) for any positive integer n, but does not use a for loop, while loop, or recursion.
(c) Write a script WeirdSumTest.m that compares the speed of WeirdSumForLoop.m and WeirdSumNoLoop.m for large values of n. Comment on the di?erences between the speed.
Explanation / Answer
a) weired sum using for loop
function result=WeirdSum(n)
sum=0;
for i=1:n-1
if i%3==0 and if i%4==0
continue;
elseif i%3==0
sum+=i;
elseif i%4==0
sum+=i;
end
return sum;
end
b)weired sum without for loop
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.