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

For homework, I need to return the remainder after dividing num1 by num2 WITHOUT using the built-in modulo operator (%). I can get most of the tests to go through with the following code, but I'm stuck on how to account for the - / + signs of given numbers. I need to transfer any character to num1, and also return a positive number, if num2 is negative - it blows to my mind how to do this ... :) Any clarity would be greatly appreciated! I'm not quite looking for an answer right here, especially since I don't seem to see anything 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
+4
source share
2 answers

. :

num1, , 2

, , . , num2 , num1 .

, num1 , , . num2 .

, ( , ), , , , num1 original .

function modulo(num1, num2) {
  var sign = num1 < 0 ? -1 : 1;
  var dividend = Math.abs(num1);
  var divisor = Math.abs(num2);

  if (dividend === 0) {
    return 0;
  }
  if (dividend === 0 || isNaN(dividend) || isNaN(divisor)) {
    return NaN;
  }
  if (dividend < divisor) {
    return sign * dividend;
  }
  
  var counter = dividend;
  while (counter >= divisor) {
    counter = counter - divisor;
  }
  return sign * counter;
}

console.log( 25 %  4, modulo( 25,  4));
console.log(-25 %  4, modulo(-25,  4));
console.log( 25 % -4, modulo( 25, -4));
console.log(-25 % -4, modulo(-25, -4));
.as-console-wrapper{min-height:100%;}
Hide result
-1

, , , case. , :

2 a b, mod(a,b), :

q = a / b;  //finding quotient (integer part only)
p = q * b;  //finding product
remainder = a - p;  //finding modulus

, JS. , , , !

: , , , :

function modulo(a,b){
  q = parseInt(a / b);  //finding quotient (integer part only)
  p = q * b;  //finding product
  return a - p;  //finding modulus
}

, %

+3

Source: https://habr.com/ru/post/1671907/


All Articles