Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a remainder without the modulo (%) operator in Javascript, accounting for -/+ sign

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
like image 473
R. Noble Avatar asked Mar 09 '17 16:03

R. Noble


People also ask

How do you return a remainder in JavaScript?

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.

What is the purpose modulo (%) operator in JavaScript?

The modulus operator ( % ) returns the division remainder.

How do you mod a negative number in JavaScript?

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.


1 Answers

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 %

like image 76
Pabs123 Avatar answered Sep 18 '22 23:09

Pabs123