In: Computer Science
Write a function divisibleBy3 with 2 positive integer inputs, a lower bound and an upper bound. Generate a list of integers from the lower bound to the upper bound and determine how many numbers in the list have a remainder equal to zero when dividing by 3.
Hint: Use a loop and the MATLAB built-in function rem to calculate the remainder after division. The remainder of N divided by P is rem(N,P).
In this I have applies a for loop in which the iterator valriable a , starts from lower_bound to upper bound and on each iteration checking whether the number is divisible by 3 or not , by using the rem function and checking if the value returned by rem function is 0 , so then the number will be divisible by 3 , so adding 1 in the result variable.
The code will be :-
lower_bound = 12 % initalising lower bound with
random value
upper_bound = 13 % initialising upper bound with random
value
function result =
divisibleby3(lower_bound,upper_bound) %function calculates the
number having remainder 0
result = 0 % initialising result variable with 0
for a = lower_bound:upper_bound % applying a for loop starting from
lower_bound till upper_bound
if rem(a,3) == 0 % checking if the remainder is 0 or not
result = result + 1; % if the remainder is 0 adding 1 to result
value
end
end
end
result = divisibleby3(12,21) % output will be "result = 4"