Skip to content

Commit b5c88b3

Browse files
authored
Merge pull request #1667 from Abhinavcode13/patch-30
Create op.js
2 parents 0677bd4 + 9f26378 commit b5c88b3

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Math/op.js

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
function divide(dividend, divisor) {
2+
// Handle special cases
3+
if (divisor === 0) {
4+
throw new Error("Division by zero");
5+
}
6+
if (dividend === 0) {
7+
return 0;
8+
}
9+
10+
// Determine the sign of the result
11+
const negativeResult = (dividend < 0) ^ (divisor < 0);
12+
13+
// Make dividend and divisor positive for easier calculations
14+
dividend = Math.abs(dividend);
15+
divisor = Math.abs(divisor);
16+
17+
let quotient = 0;
18+
19+
while (dividend >= divisor) {
20+
dividend -= divisor;
21+
quotient++;
22+
}
23+
24+
if (negativeResult) {
25+
quotient = -quotient;
26+
}
27+
28+
// Check for overflow
29+
if (quotient < -(2**31) || quotient > 2**31 - 1) {
30+
return 2**31 - 1; // Return INT_MAX for overflow
31+
}
32+
33+
return quotient;
34+
}
35+
36+
// Example usage:
37+
const dividend = 10;
38+
const divisor = 3;
39+
const result = divide(dividend, divisor);
40+
console.log(result); // Output should be 3

0 commit comments

Comments
 (0)