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

Viewed 92

I have written this

function r = remainder(n,d) % n>=0, d>0
    if d == 0
    r = 0;
    else
    r = rem(n,d);
    end
end

but it's not a recursive function

2 Answers

Not quite sure if this breaks down anywhere, but I'm sure with some testing and logical overview that can be validated. Here is a function that calls itself repeatedly to find the remainder after division. This breaks down the rem() remainder function into a recursive subtraction by the divisor until the remaining residual amount is smaller than the divisor. They're some additional guard if-statements for the cases with involving a divisor or number of 0.

Function Call:

Find_Remainder(4,5)

Function:

function [Remainder] = Find_Remainder(Number,Divisor)

if(Divisor > 0)

if(Number >= Divisor)
Remainder = Number - Divisor;

if(Remainder >= Divisor)
%Recursively calling the "Find_Remainder() function%
[Remainder] = Find_Remainder(Remainder,Divisor);
end

end

if(Number < Divisor)
Remainder = Number;
end
end

end    

Test Script for Checking:

clc;
Number = 91;
Divisor = 71;

Find_Remainder(Number,Divisor)
rem(Number,Divisor)

Ran using MATLAB R2019b

If we use abs, we can create a shorter recursive function that work with n,d ∈ ℤ:

function r = reminds(n,d)
    x = abs(n)-abs(d);
    if x < 0
        r = n;
    else
        reminds(x*sign(n),d)
    end
end

Noticed that the sign of d doesn't matter. Only the sign of the number n matter. rem(10,-3) and rem(10,3) both output 1.


If n,d ∈ R the function is even simpler:

function r = reminds(n,d)
    if n-d < 0
        r = n;
    else
        reminds(n-d,d)
    end
end
Related