write a recursive funktion that calculates the remainder r when n >= 0 is divided by d > 0
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
Michael
el 2 de Nov. de 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
Respuestas (1)
Gouri Chennuru
el 5 de Nov. de 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 comentarios
Ver también
Categorías
Más información sobre Whos en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!