Monday, 21 December 2015

Kata Day 26: Finding Remainder Without Using '%' Operator


Problem Description: You have to write a function remainder which takes two arguments : D(Dividend) and d(Divisor) and returns the remainder when D(Dividend) is divided by d(Divisor).

Assumptions:

The Arguments will always be an Integer.
D(Dividend) will always be greater than or equal to d(Divisor).
Note:

Make sure that the implemented remainder function works exactly same as the Modulus Operator(%) does i.e. m % 0 = NaN  ∀ m ∈ ℕ the only difference would be that here 'NaN' will be a string.

Level:7kyu

Link to Kata: Remainder without modulus

In this Kata we have to find the remainder when a number D(Dividend) is divided by d(Divisor) but without using a modulus operator. We know that when we are using a modulus operator what we are actually doing is subtracting the divisor from the dividend for a number of times. So for example if we have to find remainder of 13 divided by 2 we would subtract 2 from 13 6 times and then we will be left with 1 as our remainder as we cannot subtract 2 any further.

In this Kata we check that if the divisor is 0 then we would just return a string "NaN" avoiding the division by zero. Else we would subtract product of Math.floor(D/d)  and d from D.

So here if D=13 and d=2 then D/d comes out to be 6.5 and after using Math.floor() function it comes out to be 6 which we multiply by 2 and get a product as 12 and subtract this product from 13 and get our remainder as 1.

Here is a link to the code: Kata Day 26

Please mention your suggestions or your doubts in the comment below.


Happy coding. :)


No comments:

Post a Comment