-
-
Save arthurvasconcelos/65c40a2a9324a23661ae776f905516d9 to your computer and use it in GitHub Desktop.
JavaScript divide function without using "/"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Multiplication and division rules... ((+)*(+)=+) ((-)*(-)=+) ((+)*(-)=-) ((-)*(+)=-) | |
const multiply = (x, y) => { | |
let r = Math.exp(Math.log(Math.abs(x)) + Math.log(Math.abs(y))).toFixed(2) | |
return Number((x < 0 && y < 0) ? r : (x < 0 || y < 0) ? -r : r) | |
} | |
const divide = (x, y) => { | |
return (x === 0) ? 0 : multiply(((multiply(x, y) < 0) ? -1.0 : 1.0), Math.exp(Math.log(Math.abs(x)) - Math.log(Math.abs(y)))) | |
} | |
// result -66.6 | |
console.log(divide(-133.2, 2)) | |
// result 2.5 | |
console.log(divide(5, 2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment