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);
source
share