Given the two integers, dividend and divisor. Divide without using the mod, division, or multiplication operators and return the quotient.
The fractional portion of the integer division should be lost as it truncates toward zero.
As an illustration, 8.345 and -2.7335 would be reduced to 8 and -2 respectively.
Input : Dividend = 10 , Divisor = 3
Output : 3
Explanation : 10/3 = 3.33 , truncated to 3.
Input : Dividend = 7 , Divisor = -3
Output : -2
Explanation : 7/-3 = -2.33 , truncated to -2.
Input : Dividend = 7 , Divisor = 2
The brute force way to solve this problem is to repeatedly add the divisor until the sum is smaller than the dividend.
What if the divisor and dividend are identical?
To save the computation, directly 1 can be returned.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to divide two numbers
without multiplication and division */
int divide(int dividend, int divisor) {
// Base case
if(dividend == divisor) return 1;
// Variable to store the sign of result
bool isPositive = true;
// Updating the sign of quotient
if(dividend >= 0 && divisor < 0)
isPositive = false;
else if(dividend < 0 && divisor > 0)
isPositive = false;
// Storing absolute dividend & divisor
int n = abs(dividend);
int d = abs(divisor);
// Variable to store the answer and sum
int ans = 0, sum = 0;
/* Looping while sum added to divisor is
less than or equal to divisor */
while(sum + d <= n) {
// Increment the count
ans++;
// Update the sum
sum += d;
}
// Handling overflowing condition
if(ans > INT_MAX && isPositive)
return INT_MAX;
if(ans > INT_MAX && !isPositive)
return INT_MIN;
/* Returning the quotient
with proper sign */
return isPositive ? ans : -1*ans;
}
};
int main() {
int dividend = 10, divisor = 3;
/* Creating an instance of
Solution class */
Solution sol;
/* Function call to divide two numbers
without multiplication and division */
int ans = sol.divide(dividend, divisor);
cout << "The result of dividing " << dividend << " and " << divisor << " is " << ans;
return 0;
}
class Solution {
/* Function to divide two numbers
without multiplication and division */
public int divide(int dividend, int divisor) {
// Base case
if (dividend == divisor) return 1;
// Variable to store the sign of result
boolean isPositive = true;
// Updating the sign of quotient
if (dividend >= 0 && divisor < 0)
isPositive = false;
else if (dividend < 0 && divisor > 0)
isPositive = false;
// Storing absolute dividend & divisor
int n = Math.abs(dividend);
int d = Math.abs(divisor);
// Variable to store the answer and sum
int ans = 0, sum = 0;
/* Looping while sum added to divisor is
less than or equal to divisor */
while (sum + d <= n) {
// Increment the count
ans++;
// Update the sum
sum += d;
}
// Handling overflowing condition
if (ans > Integer.MAX_VALUE && isPositive)
return Integer.MAX_VALUE;
if (ans > Integer.MAX_VALUE && !isPositive)
return Integer.MIN_VALUE;
/* Returning the quotient
with proper sign */
return isPositive ? ans : -1 * ans;
}
public static void main(String[] args) {
int dividend = 10, divisor = 3;
/* Creating an instance of
Solution class */
Solution sol = new Solution();
/* Function call to divide two numbers
without multiplication and division */
int ans = sol.divide(dividend, divisor);
System.out.println("The result of dividing " + dividend + " and " + divisor + " is " + ans);
}
}
class Solution:
# Function to divide two numbers
# without multiplication and division
def divide(self, dividend, divisor):
# Base case
if dividend == divisor:
return 1
# Variable to store the sign of result
isPositive = True
# Updating the sign of quotient
if dividend >= 0 and divisor < 0:
isPositive = False
elif dividend < 0 and divisor > 0:
isPositive = False
# Storing absolute dividend & divisor
n = abs(dividend)
d = abs(divisor)
# Variable to store the answer and sum
ans = 0
sum = 0
# Looping while sum added to divisor is
# less than or equal to divisor
while sum + d <= n:
# Increment the count
ans += 1
# Update the sum
sum += d
# Handling overflowing condition
if ans > 2**31 - 1 and isPositive:
return 2**31 - 1
if ans > 2**31 - 1 and not isPositive:
return -2**31
# Returning the quotient
# with proper sign
return ans if isPositive else -1 * ans
if __name__ == "__main__":
dividend = 10
divisor = 3
# Creating an instance of
# Solution class
sol = Solution()
# Function call to divide two numbers
# without multiplication and division
ans = sol.divide(dividend, divisor)
print(f"The result of dividing {dividend} and {divisor} is {ans}")
class Solution {
/* Function to divide two numbers
without multiplication and division */
divide(dividend, divisor) {
// Base case
if (dividend === divisor) return 1;
// Variable to store the sign of result
let isPositive = true;
// Updating the sign of quotient
if (dividend >= 0 && divisor < 0)
isPositive = false;
else if (dividend < 0 && divisor > 0)
isPositive = false;
// Storing absolute dividend & divisor
let n = Math.abs(dividend);
let d = Math.abs(divisor);
// Variable to store the answer and sum
let ans = 0, sum = 0;
/* Looping while sum added to divisor is
less than or equal to divisor */
while (sum + d <= n) {
// Increment the count
ans++;
// Update the sum
sum += d;
}
// Handling overflowing condition
if (ans > Number.MAX_SAFE_INTEGER && isPositive)
return Number.MAX_SAFE_INTEGER;
if (ans > Number.MAX_SAFE_INTEGER && !isPositive)
return Number.MIN_SAFE_INTEGER;
/* Returning the quotient
with proper sign */
return isPositive ? ans : -1 * ans;
}
}
const main = () => {
let dividend = 10, divisor = 3;
/* Creating an instance of
Solution class */
let sol = new Solution();
/* Function call to divide two numbers
without multiplication and division */
let ans = sol.divide(dividend, divisor);
console.log(`The result of dividing ${dividend} and ${divisor} is ${ans}`);
};
main();
Time Complexity: O(dividend)
In the worst case when the divisor is 1, the number of iterations taken will be O(dividend).
Space Complexity: O(1) Using a couple of variables i.e., constant space.
The key idea is to repeatedly subtract the divisor from the dividend until the dividend is smaller than the divisor. However, doing this one step at a time can be very slow, so we use a method that speeds up the process by leveraging bit manipulation.
An important concept to know is that the quotient can be expressed as the sum of powers of 2.
Example: Dividend = 10, Divisor = 3.
Quotient = 10/3 = 3 which can be represented as 21 + 20.
Now, instead of subtracting the divisor from the dividend one unit at a time, we use powers of 2 (using bit shifting) to subtract larger multiples of the divisors in each step. This makes the process faster.
What if the divisor and dividend are identical?
To save the computation, directly 1 can be returned.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to divide two numbers
without multiplication and division */
int divide(int dividend, int divisor) {
// Base case
if(dividend == divisor) return 1;
// Variable to store the sign of result
bool isPositive = true;
// Updating the sign of quotient
if(dividend >= 0 && divisor < 0)
isPositive = false;
else if(dividend < 0 && divisor > 0)
isPositive = false;
// Storing absolute dividend & divisor
int n = abs(dividend);
int d = abs(divisor);
// Variable to store the answer
int ans = 0;
/* Looping while dividend is
greater than equal to divisor */
while(n >= d) {
int count = 0;
/* Finding the required
largest power of 2 */
while(n >= (d << (count+1))) {
count++;
}
// Updating the answer & dividend
ans += (1 << count);
n -= d*(1 << count);
}
// Handling overflowing condition
if(ans > INT_MAX && isPositive)
return INT_MAX;
if(ans > INT_MAX && !isPositive)
return INT_MIN;
/* Returning the quotient
with proper sign */
return isPositive ? ans : -1*ans;
}
};
int main() {
int dividend = 10, divisor = 3;
/* Creating an instance of
Solution class */
Solution sol;
/* Function call to divide two numbers
without multiplication and division */
int ans = sol.divide(dividend, divisor);
cout << "The result of dividing " << dividend << " and " << divisor << " is " << ans;
return 0;
}
class Solution {
/* Function to divide two numbers
without multiplication and division */
public int divide(int dividend, int divisor) {
// Base case
if(dividend == divisor) return 1;
// Variable to store the sign of result
boolean isPositive = true;
// Updating the sign of quotient
if(dividend >= 0 && divisor < 0)
isPositive = false;
else if(dividend < 0 && divisor > 0)
isPositive = false;
// Storing absolute dividend & divisor
int n = Math.abs(dividend);
int d = Math.abs(divisor);
// Variable to store the answer
int ans = 0;
/* Looping while dividend is
greater than equal to divisor */
while(n >= d) {
int count = 0;
/* Finding the required
largest power of 2 */
while(n >= (d << (count+1))) {
count++;
}
// Updating the answer & dividend
ans += (1 << count);
n -= d*(1 << count);
}
// Handling overflowing condition
if(ans > Integer.MAX_VALUE && isPositive)
return Integer.MAX_VALUE;
if(ans > Integer.MAX_VALUE && !isPositive)
return Integer.MIN_VALUE;
/* Returning the quotient
with proper sign */
return isPositive ? ans : -1*ans;
}
public static void main(String[] args) {
int dividend = 10, divisor = 3;
/* Creating an instance of
Solution class */
Solution sol = new Solution();
/* Function call to divide two numbers
without multiplication and division */
int ans = sol.divide(dividend, divisor);
System.out.println("The result of dividing " + dividend + " and " + divisor + " is " + ans);
}
}
class Solution:
# Function to divide two numbers
# without multiplication and division
def divide(self, dividend, divisor):
# Base case
if dividend == divisor: return 1
# Variable to store the sign of result
isPositive = True
# Updating the sign of quotient
if dividend >= 0 and divisor < 0:
isPositive = False
elif dividend < 0 and divisor > 0:
isPositive = False
# Storing absolute dividend & divisor
n = abs(dividend)
d = abs(divisor)
# Variable to store the answer
ans = 0
# Looping while dividend is
# greater than equal to divisor
while n >= d:
count = 0
# Finding the required
# largest power of 2
while n >= (d << (count+1)):
count += 1
# Updating the answer & dividend
ans += (1 << count)
n -= d * (1 << count)
# Handling overflowing condition
if ans > 2**31 - 1 and isPositive:
return 2**31 - 1
if ans > 2**31 - 1 and not isPositive:
return -2**31
# Returning the quotient
# with proper sign
return ans if isPositive else -1 * ans
# Main function to test the solution
dividend = 10
divisor = 3
# Creating an instance of
# Solution class
sol = Solution()
# Function call to divide two numbers
# without multiplication and division
ans = sol.divide(dividend, divisor)
print(f"The result of dividing {dividend} and {divisor} is {ans}")
class Solution {
/* Function to divide two numbers
without multiplication and division */
divide(dividend, divisor) {
// Base case
if (dividend === divisor) return 1;
// Variable to store the sign of result
let isPositive = true;
// Updating the sign of quotient
if (dividend >= 0 && divisor < 0)
isPositive = false;
else if (dividend < 0 && divisor > 0)
isPositive = false;
// Storing absolute dividend & divisor
let n = Math.abs(dividend);
let d = Math.abs(divisor);
// Variable to store the answer
let ans = 0;
/* Looping while dividend is
greater than equal to divisor */
while (n >= d) {
let count = 0;
/* Finding the required
largest power of 2 */
while (n >= (d << (count + 1))) {
count++;
}
// Updating the answer & dividend
ans += (1 << count);
n -= d * (1 << count);
}
// Handling overflowing condition
if (ans > 2147483647 && isPositive)
return 2147483647;
if (ans > 2147483647 && !isPositive)
return -2147483648;
/* Returning the quotient
with proper sign */
return isPositive ? ans : -1 * ans;
}
}
// Main function to test the solution
const dividend = 10;
const divisor = 3;
/* Creating an instance of
Solution class */
const sol = new Solution();
/* Function call to divide two numbers
without multiplication and division */
const ans = sol.divide(dividend, divisor);
console.log(`The result of dividing ${dividend} and ${divisor} is ${ans}`);
Time Complexity: O((logN)2) – (where N is the absolute value of dividend)
Space Complexity: O(1) – Using a couple of variables i.e., constant space.
Q: How would you extend this for modular division?
A: After computing the quotient using bitwise operations, compute the remainder as remainder=dividend−(quotient×divisor).
Q: How would you handle floating-point division?
A: This solution works only for integers. For floating-point division, a completely different approach involving approximation or precision handling (e.g., Newton-Raphson method) would be required.
Q: Can this be done without bitwise operations?
A: Yes, you can use repeated subtraction. However, it’s inefficient for large values of the dividend and divisor. Bitwise shifting significantly improves performance.
Q: What happens if the divisor is 0?
A: Division by zero is undefined. The function should raise an exception or return an error for this invalid input.