フィルターのクリア

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

13 ビュー (過去 30 日間)
lukas förström
lukas förström 2020 年 11 月 2 日
回答済み: Gouri Chennuru 2020 年 11 月 5 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by