For a homework assignment, I need to return the remainder after dividing num1 by num2 WITHOUT using the built-in modulo (%) operator. I'm able to get most tests to pass with the following code, but I'm stuck on how to account for -/+ signs of the given numbers. I need to carry over whichever sign is on num1, and also return a positive number if the num2 is negative - it's blowing my mind how to do this... :) Any clarity would be greatly appreciated! I'm not exactly looking for the straight up answer here, more that I seem to be missing something obvious... Maybe I need a new approach?
function modulo(num1, num2) {
if (num1 === 0) {
return 0;
}
if (num2 === 0 || isNaN(num1) || isNaN(num2)) {
return NaN;
}
if (num1 < num2) {
return num1;
}
if (num1 > 0 && num2 > 0) {
var counter = num1;
while (counter >= Math.abs(num2)) {
counter = counter - num2;
}
return counter;
}
}
var output = modulo(25, 4);
console.log(output); // 1
Remainder (%)The remainder operator ( % ) returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.
The modulus operator ( % ) returns the division remainder.
For Negative Numbers: Input: a = -23, b = 4 Output: 1 Explanation: modulo = -23 % 4 modulo = -23 + 4 * 6 modulo = -23 + 24 = 1 Other Explanation: The number -23 can be written in terms of 4 as -23 = (-6) * 4 + 1 So, here '1' is the result.
If you think about the mathematical process to calculate modulus you might be able see how you can do this without having to resort to a bunch of case statements. Instead think of it this way, you're just calculating a remainder:
Given 2 numbers a and b, you can compute mod(a,b)
by doing the following:
q = a / b; //finding quotient (integer part only)
p = q * b; //finding product
remainder = a - p; //finding modulus
Using this idea, you should be able to transfer it to JS. You said you're not looking for the straight up answer so that's all I'll say!
Edit: here is the code, like I said in the comments it's exactly the pseudocode I posted above:
function modulo(a,b){
q = parseInt(a / b); //finding quotient (integer part only)
p = q * b; //finding product
return a - p; //finding modulus
}
This will return the exact same values as using %
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With