write a recursive funktion that calculates the remainder r when n >= 0 is divided by d > 0

3 次查看(过去 30 天)
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 个评论
Michael
Michael 2020-11-2
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

请先登录,再进行评论。

回答(1 个)

Gouri Chennuru
Gouri Chennuru 2020-11-5
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!

类别

Help CenterFile Exchange 中查找有关 Whos 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by