write a recursive funktion that calculates the remainder r when n >= 0 is divided by d > 0
13 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commento
Michael
il 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
Risposte (1)
Gouri Chennuru
il 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 Commenti
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!