write a recursive funktion that calculates the remainder r when n >= 0 is divided by d > 0
4 views (last 30 days)
Show older comments
I have written this but it's not a recursive function
function r = remainder(n,d) % n>=0, d>0
if d == 0
r = 0;
else
r = rem(n,d);
end
end
1 Comment
Michael
on 2 Nov 2020
When writing recursive functions, you must use the name of the function in the function itself.
rem(n,d) is built in matlab code which will return the remainder as long as d is not equal to zero.
In order to write a recursive function, you must work towards your base case, which here is d ==0. I do not advise looking at d, and instead think your base case(s) should be related to n.
Hope those hints in the final lines help,
Michael
Answers (1)
Gouri Chennuru
on 5 Nov 2020
Hi
The process of the function calling itself multiple times is known as recursion, and a function that implements it is a recursive function.
In the code which you have mentioned the rem() is the inbuilt function and user defined function remainder() is not calling itself again and again so it is not a recursive function.
As a workaround, you can use the following code snippet in order to calculate the remainder using recurrsive functions.
function r = remainder(n,d) % n>=0, d>0
if n < d % base condition
r = n;
else
r = remainder(n-d,d); % Process of recursion
end
end
Hope this Helps!
0 Comments
See Also
Categories
Find more on Whos in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!