1. Repeated Subtraction
Intuition
Determine the sign. Convert both numbers to positive absolute values. While dividend >= divisor, subtract divisor and increment quotient. Apply sign and check overflow limits.
When to apply: Conceptual explanation of division as repeated subtraction.
Algorithm
- Step 1: Guard against INT_MIN / -1 overflow.
- Step 2: Determine sign: negative if (dividend < 0) ^ (divisor < 0).
- Step 3: Loop while absDividend >= absDivisor: absDividend -= absDivisor, count++.
- Step 4: Return sign ? -count : count.
#include <iostream>#include <climits>#include <cmath> using namespace std; int divideBrute(int dividend, int divisor) { if (dividend == INT_MIN && divisor == -1) return INT_MAX; bool isNeg = (dividend < 0) ^ (divisor < 0); long long a = abs((long long)dividend); long long b = abs((long long)divisor); long long count = 0; while (a >= b) { a -= b; count++; } return isNeg ? (int)-count : (int)count;} int main() { cout << "Brute (10, 3): " << divideBrute(10, 3) << endl; // 3 cout << "Brute (7, -3): " << divideBrute(7, -3) << endl; // -2 return 0;}Time & Space Complexity
- Time complexity:
O(dividend / divisor) - Space complexity:
O(1)