Skip to content

Instantly share code, notes, and snippets.

@unilecs
Created October 15, 2017 13:49
Show Gist options
  • Save unilecs/7654ca5aaec3f23772ed151d2aa97a43 to your computer and use it in GitHub Desktop.
Save unilecs/7654ca5aaec3f23772ed151d2aa97a43 to your computer and use it in GitHub Desktop.
Операции вычитания, умножения и деления через операцию сложения
function getNegative(x) {
let neg = 0;
let sign = x < 0 ? 1 : -1;
while (x !== 0) {
neg += sign;
x += sign;
}
return neg;
}
function subtract(first, second) {
return first + getNegative(second);
}
function multiply(first, second) {
if (first < second) {
return multiply(second, first); // алгоритм будет быстрее, если second < first
}
let sum = 0;
for (let i = Math.abs(second); i > 0; i--) {
sum += first;
}
if (second < 0) {
sum = getNegative(sum);
}
return sum;
}
function divide(first, second) {
if (second === 0) {
return null; // error: dividing by zero
}
let absFirst = Math.abs(first), absSecond = Math.abs(second);
let product = 0, result = 0;
while (product + absSecond <= absFirst) {
product += absSecond;
result++;
}
if ((first < 0 && second < 0) || (first > 0 && second > 0)) {
return result;
} else {
return getNegative(result);
}
}
console.info(subtract(2, 4));
console.info(multiply(3, -4));
console.info(divide(12, -4));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment