Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
1.1.
Problem Statement:
1.2.
Example
2.
Brute Force
2.1.
Algorithm
2.2.
Implementation:
2.2.1.
Program:
2.3.
C
2.4.
C++
2.5.
Java
2.6.
Python
2.7.
Javascript
2.8.
C#
2.8.1.
Input:
2.8.2.
Output:
2.9.
Time Complexity
2.10.
Space Complexity
3.
Binary Search
3.1.
Algorithm
3.2.
Implementation:
3.2.1.
Program: 
3.3.
C
3.4.
C++
3.5.
Java
3.6.
Python
3.7.
Javascript
3.8.
C#
3.8.1.
Input:
3.8.2.
Output:
3.9.
Time Complexity
3.10.
Space Complexity
4.
Bit Manipulation
4.1.
Algorithm
4.2.
Implementation:
4.2.1.
Program 
4.3.
C
4.4.
C++
4.5.
Java
4.6.
Python
4.7.
Javascript
4.8.
C#
4.8.1.
Input:
4.8.2.
Output:
4.9.
Time Complexity
4.10.
Space Complexity
5.
Frequently Asked Questions
5.1.
Why might dividing two integers lead to unexpected results in programming languages?
5.2.
How can I handle edge cases like division by zero or integer overflow when dividing integers in my code?
5.3.
What are some alternative approaches to integer division beyond simple arithmetic operators?
6.
Conclusion
Last Updated: May 4, 2024
Easy

Divide Two Integers

Author Ishita Chawla
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

Bit Manipulation and Binary Search are some of the few topics that students generally neglect while focusing on other important topics of Data Structures and Algorithms. However, when applied to questions, these topics enhance the time and space complexity of the problem and make the solution relatively easy and understandable.

Divide Two Integers

Today we will discuss one such significant problem, Divide Two Integers that can easily be solved using Bitwise operators and binary search, and see how brute force may sometimes become inefficient and generate errors like Time Limit Exceed.

Problem Statement:

You have been given two integers, a dividend, and a divisor. The problem states that you have to divide two integers, the dividend, and divisor without using multiplication, division, or mod operator. Also, the function must return the floor value of the quotient. 

Assumption→ We assume that we are dealing with an environment that can store integers only within the 32-bit signed integer range, i.e., [- 231, 231 - 1].

So assume that your function returns 231 - 1 when the division result overflows.

Example

 

          1.  DIVIDEND = 10

    DIVISOR =  3

    QUOTIENT = 10 / 3 = 3.333…. = 3 (Floor value)

 

           2.  DIVIDEND = 100

      DIVISOR =  -16

      QUOTIENT = 100 / -16 = - 6.25 = -6 (Floor value)


 3. DIVIDEND = -56

    DIVISOR =  -14

    QUOTIENT = -56 / -14 = -4 

 

           4. DIVIDEND = -99

     DIVISOR =  7

     QUOTIENT = -99 / 7 = -14.1428… = -14 (Floor value)

Brute Force

Algorithm

  • The question states that we cannot use the multiplication, division, or mod operator to divide two integers.
  • So, we will make use of subtraction to find the answer.
  • We will keep subtracting the divisor from the dividend and keep a count of the number of subtractions.
  • This count is equal to the quotient of the two numbers.
  • Also, we need to keep track of the sign of the dividend and the divisor.

Implementation:

Program:

  • C
  • C++
  • Java
  • Python
  • Javascript
  • C#

C

#include <stdio.h>
#include <limits.h>
#include <stdlib.h>

int divide(int dividend, int divisor) {
if (divisor == 1)
return dividend;

if (dividend == INT_MIN) {
dividend++;
}

int sign = -1, quotient = 0;
if ((dividend < 0 && divisor < 0) || (dividend >= 0 && divisor >= 0))
sign = 1;

dividend = abs(dividend);
divisor = abs(divisor);

while (dividend >= divisor) {
dividend -= divisor;
quotient++;
}

return quotient * sign;
}

int main() {
int dividend, divisor;

printf("Enter the dividend and divisor: ");
scanf("%d %d", &dividend, &divisor);

printf("The quotient is %d", divide(dividend, divisor));

return 0;
}

C++

// C++ program to divide two numbers using brute force.
#include <iostream>
#include <climits>
using namespace std;

// Function to find the quotient.
int divide(int dividend, int divisor)
{
if (divisor == 1)
return dividend;

if (dividend == INT_MIN)
{
dividend++;
}

// Initialising the sign as 1 and quotient as 0.
int sign = -1, quotient = 0;

// If one of the dividends or divisor is negative, the sign becomes negative.
if ((dividend < 0 && divisor < 0) || (dividend >= 0 && divisor >= 0))
sign = 1;

// Taking positive values of both dividend and divisor.
dividend = abs(dividend);
divisor = abs(divisor);

// Calculating the value of quotient.
while (dividend >= divisor)
{
dividend -= divisor;
quotient++;
}

// Returning the answer by multiplying the sign with the quotient.
return quotient * sign;
}
int main()
{
int dividend, divisor;

// Taking user input.
cout << "Enter the dividend and divisor: ";
cin >> dividend >> divisor;

// Calling the function and printing the answer.
cout << "The quotient is " << divide(dividend, divisor);

return 0;
}

Java

import java.util.Scanner;

public class Main {
public static int divide(int dividend, int divisor) {
if (divisor == 1)
return dividend;

if (dividend == Integer.MIN_VALUE) {
dividend++;
}

int sign = -1, quotient = 0;
if ((dividend < 0 && divisor < 0) || (dividend >= 0 && divisor >= 0))
sign = 1;

dividend = Math.abs(dividend);
divisor = Math.abs(divisor);

while (dividend >= divisor) {
dividend -= divisor;
quotient++;
}

return quotient * sign;
}

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the dividend and divisor: ");
int dividend = scanner.nextInt();
int divisor = scanner.nextInt();

System.out.println("The quotient is " + divide(dividend, divisor));
}
}

Python

def divide(dividend, divisor):
if divisor == 1:
return dividend

if dividend == -2147483648:
dividend += 1

sign, quotient = -1, 0
if (dividend < 0 and divisor < 0) or (dividend >= 0 and divisor >= 0):
sign = 1

dividend = abs(dividend)
divisor = abs(divisor)

while dividend >= divisor:
dividend -= divisor
quotient += 1

return quotient * sign

def main():
dividend, divisor = map(int, input("Enter the dividend and divisor: ").split())
print("The quotient is", divide(dividend, divisor))

if __name__ == "__main__":
main()

Javascript

function divide(dividend, divisor) {
if (divisor === 1)
return dividend;

if (dividend === -2147483648) {
dividend += 1;
}

let sign = -1, quotient = 0;
if ((dividend < 0 && divisor < 0) || (dividend >= 0 && divisor >= 0))
sign = 1;

dividend = Math.abs(dividend);
divisor = Math.abs(divisor);

while (dividend >= divisor) {
dividend -= divisor;
quotient++;
}

return quotient * sign;
}

function main() {
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});

rl.question("Enter the dividend and divisor: ", (input) => {
const [dividend, divisor] = input.split(' ').map(Number);
console.log("The quotient is", divide(dividend, divisor));
rl.close();
});
}

main();

C#

using System;

class Program {
static int divide(int dividend, int divisor) {
if (divisor == 1)
return dividend;

if (dividend == int.MinValue) {
dividend++;
}

int sign = -1, quotient = 0;
if ((dividend < 0 && divisor < 0) || (dividend >= 0 && divisor >= 0))
sign = 1;

dividend = Math.Abs(dividend);
divisor = Math.Abs(divisor);

while (dividend >= divisor) {
dividend -= divisor;
quotient++;
}

return quotient * sign;
}

static void Main(string[] args) {
Console.Write("Enter the dividend and divisor: ");
string[] inputs = Console.ReadLine().Split(' ');
int dividend = int.Parse(inputs[0]);
int divisor = int.Parse(inputs[1]);

Console.WriteLine("The quotient is " + divide(dividend, divisor));
}
}

Input:

Enter the dividend and divisor: -14 -2

 

Output:

The quotient is 7.

 

Time Complexity

The time complexity of this approach is O(abs(M - N) / N), whereis the dividend and N is the divisor.

The time complexity is linear since we traverse the numbers between M - N and divide them by N.

Space Complexity

The space complexity of this approach is O(1).

Since we are not using any extra space to store the numbers, the space complexity of this solution is constant, i.e. O(1).
 

NOTE→ Though this approach is correct, it will not be accepted as the problem’s solution because of the constraints. The IDE will always throw a Time Limit Exceed on test cases where the dividend is too large, and the divisor is too small.

Read More - Time Complexity of Sorting Algorithms, and Euclid GCD Algorithm

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Binary Search

Algorithm

  • For a given dividend and divisor, we know that 

QUOTIENT * DIVISOR <= DIVIDEND

  • So for any number X, which is greater than the quotient, 

X * DIVISOR >= DIVIDEND

  • Similarly, for a number Y, which is less than the quotient,

Y * DIVISOR >= DIVIDEND

  • We know that the quotient will lie between 0 and the dividend.
  • So we perform a binary search on this given range, i.e., from 0 to dividend.
  • If MID * DIVISOR > DIVIDEND, we go towards the left and make HI = MID -1.
  • Else we go towards the right and make LOW = MID + 1.
  • The value of MID that satisfies the condition will be our quotient.

Let’s try to understand this with the help of an example:
 

Suppose,  

          DIVIDEND = 10

          DIVISOR =  3

          QUOTIENT = 0

  •                 LOW = 0

HIGH = 10

0 <= 10

Thus,  MID = (0 + 10) / 2

                   = 5

Now, MID * DIVISOR = 5 * 3

                                                       = 15 (> DIVIDEND)

                    So, HIGH = MID - 1

                                     = 5 - 1

                                     = 4

                    QUOTIENT = 0

  •                   LOW = 0

  HIGH = 4

 0 <= 4

  Thus,  MID = (0 + 4) / 2

                    = 2

Now, MID * DIVISOR = 2 * 3

                                                       = 6 (< DIVIDEND)

                     So, LOW = MID + 1

                                     = 2 + 1

                                     = 3

            QUOTIENT = MID = 2

  •                  LOW = 3

HIGH = 4

3 <= 4

Thus,  MID = (3 + 4) / 2

                   = 3

 

                   Now, MID * DIVISOR = 3 * 3

                                                      = 9 (< DIVIDEND)

                   So, LOW = MID + 1

                                   = 3 + 1

                                   = 4

                   QUOTIENT = MID = 3

  •                 LOW = 4

HIGH = 4

4 <= 4

Thus,  MID = (4 + 4) / 2

                  = 4

Now, MID * DIVISOR = 4 * 3

                                                        = 12 (> DIVIDEND)

                    So, HIGH = MID - 1

                                     = 4 - 1

                                     = 3

                    QUOTIENT = 3

Thus, the quotient when 10 is divided byis 3.

Implementation:

Program:
 

  • C
  • C++
  • Java
  • Python
  • Javascript
  • C#

C

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int divide(int dividend, int divisor) {
unsigned long long int lo = 0;
unsigned long long int hi = abs(dividend);

if (dividend == INT_MIN) {
if (divisor == -1)
return INT_MAX;
else if (divisor == 1)
return INT_MIN;
}

int quotient = 0;

while (lo <= hi) {
unsigned long long int mid = (lo + hi) / 2;
if (abs(divisor) * mid <= abs(dividend)) {
quotient = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}

return ((dividend < 0 && divisor < 0) || (dividend >= 0 && divisor >= 0) ? quotient : -quotient);
}

int main() {
int dividend, divisor;
printf("Enter the dividend and divisor: ");
scanf("%d %d", &dividend, &divisor);
printf("The quotient is %d", divide(dividend, divisor));
return 0;
}

C++

// C++ program to divide two numbers using binary search.
#include <iostream>
#include <climits>
using namespace std;

// Function to find the quotient.
int divide(int dividend, int divisor)
{
unsigned long long int lo = 0;
unsigned long long int hi = abs(dividend);

// Checking the condition for overflow.
if (dividend == INT_MIN)
{
if (divisor == -1)
{
return INT_MAX;
}
else if (divisor == 1)
{
return INT_MIN;
}
}

int quotient = 0;

// Performing binary search on the given range of numbers.
while (lo <= hi)
{
unsigned long long int mid = (lo + hi) / 2;
if (abs(divisor) * mid <= abs(dividend))
{
quotient = mid;
lo = mid + 1;
}
else
{
hi = mid - 1;
}
}

// Checking the parity of the answer and returning it accordingly.
return ((dividend < 0 && divisor < 0) || (dividend >= 0 && divisor >= 0) ? quotient : -quotient);
}
int main()
{
int dividend, divisor;

// Taking user input.
cout << "Enter the dividend and divisor: ";
cin >> dividend >> divisor;

// Calling the function and printing the answer.
cout << "The quotient is " << divide(dividend, divisor);

return 0;
}

Java

import java.util.Scanner;

public class Main {
public static int divide(int dividend, int divisor) {
long lo = 0;
long hi = Math.abs((long) dividend);

if (dividend == Integer.MIN_VALUE) {
if (divisor == -1)
return Integer.MAX_VALUE;
else if (divisor == 1)
return Integer.MIN_VALUE;
}

int quotient = 0;

while (lo <= hi) {
long mid = (lo + hi) / 2;
if (Math.abs(divisor) * mid <= Math.abs(dividend)) {
quotient = (int) mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}

return ((dividend < 0 && divisor < 0) || (dividend >= 0 && divisor >= 0) ? quotient : -quotient);
}

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the dividend and divisor: ");
int dividend = scanner.nextInt();
int divisor = scanner.nextInt();
System.out.println("The quotient is " + divide(dividend, divisor));
}
}

Python

def divide(dividend, divisor):
lo = 0
hi = abs(dividend)

if dividend == -2147483648:
if divisor == -1:
return 2147483647
elif divisor == 1:
return -2147483648

quotient = 0
while lo <= hi:
mid = (lo + hi) // 2
if abs(divisor) * mid <= abs(dividend):
quotient = mid
lo = mid + 1
else:
hi = mid - 1

return quotient if (dividend < 0 and divisor < 0) or (dividend >= 0 and divisor >= 0) else -quotient

def main():
dividend, divisor = map(int, input("Enter the dividend and divisor: ").split())
print("The quotient is", divide(dividend, divisor))

if __name__ == "__main__":
main()

Javascript

function divide(dividend, divisor) {
let lo = 0;
let hi = Math.abs(dividend);

if (dividend === -2147483648) {
if (divisor === -1)
return 2147483647;
else if (divisor === 1)
return -2147483648;
}

let quotient = 0;
while (lo <= hi) {
let mid = Math.floor((lo + hi) / 2);
if (Math.abs(divisor) * mid <= Math.abs(dividend)) {
quotient = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}

return ((dividend < 0 && divisor < 0) || (dividend >= 0 && divisor >= 0) ? quotient : -quotient);
}

function main() {
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});

rl.question("Enter the dividend and divisor: ", (input) => {
const [dividend, divisor] = input.split(' ').map(Number);
console.log("The quotient is", divide(dividend, divisor));
rl.close();
});
}

main();

C#

using System;

class Program {
static int Divide(int dividend, int divisor) {
long lo = 0;
long hi = Math.Abs((long)dividend);

if (dividend == int.MinValue) {
if (divisor == -1)
return int.MaxValue;
else if (divisor == 1)
return int.MinValue;
}

int quotient = 0;

while (lo <= hi) {
long mid = (lo + hi) / 2;
if (Math.Abs(divisor) * mid <= Math.Abs(dividend)) {
quotient = (int)mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}

return ((dividend < 0 && divisor < 0) || (dividend >= 0 && divisor >= 0) ? quotient : -quotient);
}

static void Main(string[] args) {
Console.Write("Enter the dividend and divisor: ");
string[] inputs = Console.ReadLine().Split(' ');
int dividend = int.Parse(inputs[0]);
int divisor = int.Parse(inputs[1]);

Console.WriteLine("The quotient is " + Divide(dividend, divisor));
}
}

Input:

Enter the dividend and divisor: 10 3

 

Output:

The quotient is 3.

 

Time Complexity

The time complexity of this approach is O(log N), where N is the DIVIDEND.

Since we have used binary search to perform the division and the time complexity of Binary Search is O(log N), where N is the number of elements in the array, so the time complexity of the solution is O(log N), where N is the DIVIDEND.

Space Complexity

The space complexity of this approach is O(1).

Since we are not using any extra space to store the numbers, the space complexity of this solution is constant, i.e., O(1).

Bit Manipulation

Algorithm

  • We find the greatest power of 2, which, when multiplied by the quotient, gives an answer that is just smaller than the dividend.
  • After finding this power, we add it to our answer.
  • We reduce the dividend by the divisor multiplied by this power of 2 found.
  • Now, we perform the above operation once again with the reduced dividend.

Let’s consider a simple example to be more clear:

Suppose,  

       DIVIDEND = 10

      DIVISOR =  3

     Let QUOTIENT denote the highest power of 2 that can be subtracted from the dividend.

    Let ANSWER store our final answer.

  •                 DIVIDEND = 10

                      DIVISOR =  3

Initially, ANSWER = 0

QUOTIENT = 0

DIVISOR << (QUOTIENT + 1)

3 << (0 + 1) = 3 << 1 = 3 * 21 = 6
10 > 6 

So, QUOTIENT = 1

3 << (1 + 1) = 3 << 2 = 3 * 22 = 12 

                    

                    But, 10 < 6

          Inner loop breaks.

 

          ANSWER = 0 + 21 = 2 

         DIVIDEND = 10 - (3 << 1) = 10 - 6 = 4 


Now,

  •                 DIVIDEND = 4

                      DIVISOR =  3

Initially, ANSWER = 2

QUOTIENT = 0

DIVISOR << (QUOTIENT + 1)

3 << (0 + 1) = 3 << 1 = 3 * 21 = 6

 

But, 4 < 6 

So, ANSWER = 2 + 20 = 2 + 1 = 3

                     DIVIDEND = 4 - (3 << 0) = 4 - 3 = 1

                     Loop breaks. 

Thus, our answer is 3.

Implementation:

Program
 

  • C
  • C++
  • Java
  • Python
  • Javascript
  • C#

C

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int divide(int dividend, int divisor) {
if (dividend == divisor)
return 1;

int isPositive = (dividend < 0 == divisor < 0);
unsigned int absDividend = abs(dividend);
unsigned int absDivisor = abs(divisor);

unsigned int ans = 0;
while (absDividend >= absDivisor) {
int quotient = 0;
while (absDividend > (absDivisor << (quotient + 1)))
quotient++;

ans += (1 << quotient);
absDividend -= (absDivisor << quotient);
}

if (ans == (1 << 31) && isPositive)
return INT_MAX;

return isPositive ? ans : -ans;
}

int main() {
int dividend, divisor;
printf("Enter the dividend and divisor: ");
scanf("%d %d", &dividend, &divisor);
printf("The quotient is %d", divide(dividend, divisor));
return 0;
}

C++

// C++ program to divide two numbers using bit manipulation.
#include <iostream>
#include <climits>

using namespace std;

// Function to find the quotient.
int divide(int dividend, int divisor)
{
// If the dividend and divisor are equal, the answer will always be 1.
if (dividend == divisor)
return 1;

// The answer is always positive if the dividend and divisor are of the same sign.
bool isPositive = (dividend < 0 == divisor < 0);

// Taking positive values of the dividend and divisor.
unsigned int absDividend = abs(dividend);
unsigned int absDivisor = abs(divisor);

unsigned int ans = 0;

// While the dividend is greater than or equal to divisor.
while (absDividend >= absDivisor)
{
int quotient = 0;
while (absDividend > (absDivisor << (quotient + 1)))
quotient++;

// This power of 2 that is found is added to the answer.
ans += (1 << quotient);

// The dividend is reduced by the divisor multiplied by the power of 2 found
absDividend -= (absDivisor << quotient);
}

// In case the answer cannot be stored in the signed int.
if (ans == (1 << 31) and isPositive)
return INT_MAX;

// Returning the answer according to the sign.
return isPositive ? ans : -ans;
}
int main()
{
int dividend, divisor;

// Taking user input.
cout << "Enter the dividend and divisor: ";
cin >> dividend >> divisor;

// Calling the function and printing the answer.
cout << "The quotient is " << divide(dividend, divisor);

return 0;
}

Java

import java.util.Scanner;

public class Main {
public static int divide(int dividend, int divisor) {
if (dividend == divisor)
return 1;

boolean isPositive = (dividend < 0 == divisor < 0);
int absDividend = Math.abs(dividend);
int absDivisor = Math.abs(divisor);

int ans = 0;
while (absDividend >= absDivisor) {
int quotient = 0;
while (absDividend > (absDivisor << (quotient + 1)))
quotient++;

ans += (1 << quotient);
absDividend -= (absDivisor << quotient);
}

if (ans == (1 << 31) && isPositive)
return Integer.MAX_VALUE;

return isPositive ? ans : -ans;
}

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the dividend and divisor: ");
int dividend = scanner.nextInt();
int divisor = scanner.nextInt();
System.out.println("The quotient is " + divide(dividend, divisor));
}
}

Python

def divide(dividend, divisor):
if dividend == divisor:
return 1

is_positive = (dividend < 0 == divisor < 0)
abs_dividend = abs(dividend)
abs_divisor = abs(divisor)

ans = 0
while abs_dividend >= abs_divisor:
quotient = 0
while abs_dividend > (abs_divisor << (quotient + 1)):
quotient += 1

ans += (1 << quotient)
abs_dividend -= (abs_divisor << quotient)

if ans == (1 << 31) and is_positive:
return 2147483647

return ans if is_positive else -ans

def main():
dividend, divisor = map(int, input("Enter the dividend and divisor: ").split())
print("The quotient is", divide(dividend, divisor))

if __name__ == "__main__":
main()

Javascript

function divide(dividend, divisor) {
if (dividend === divisor)
return 1;

const isPositive = (dividend < 0 === divisor < 0);
const absDividend = Math.abs(dividend);
const absDivisor = Math.abs(divisor);

let ans = 0;
while (absDividend >= absDivisor) {
let quotient = 0;
while (absDividend > (absDivisor << (quotient + 1)))
quotient++;

ans += (1 << quotient);
absDividend -= (absDivisor << quotient);
}

if (ans === (1 << 31) && isPositive)
return 2147483647;

return isPositive ? ans : -ans;
}

function main() {
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});

rl.question("Enter the dividend and divisor: ", (input) => {
const [dividend, divisor] = input.split(' ').map(Number);
console.log("The quotient is", divide(dividend, divisor));
rl.close();
});
}

main();

C#

using System;

class Program {
static int Divide(int dividend, int divisor) {
if (dividend == divisor)
return 1;

bool isPositive = (dividend < 0 == divisor < 0);
int absDividend = Math.Abs(dividend);
int absDivisor = Math.Abs(divisor);

int ans = 0;
while (absDividend >= absDivisor) {
int quotient = 0;
while (absDividend > (absDivisor << (quotient + 1)))
quotient++;

ans += (1 << quotient);
absDividend -= (absDivisor << quotient);
}

if (ans == (1 << 31) && isPositive)
return 2147483647;

return isPositive ? ans : -ans;
}

static void Main(string[] args) {
Console.Write("Enter the dividend and divisor: ");
string[] inputs = Console.ReadLine().Split(' ');
int dividend = int.Parse(inputs[0]);
int divisor = int.Parse(inputs[1]);

Console.WriteLine("The quotient is " + Divide(dividend, divisor));
}
}

Input:

Enter the dividend and divisor: -47 7

 

Output:

The quotient is -6.

 

Time Complexity

The time complexity of this approach is O(log N), where N is the DIVIDEND.

This is because we have used the left shift operator to perform the division, and its complexity is O(log N), where N is the DIVIDEND.

Space Complexity

The space complexity of this approach is O(1).

Since we are not using any extra space to store the numbers, the space complexity of this solution is constant, i.e., O(1).

Read about Bitwise Operators in C here.

Frequently Asked Questions

Why might dividing two integers lead to unexpected results in programming languages?

We can address the challenges of integer division, such as truncation of the fractional part and potential overflow or underflow issues, particularly in languages like C and Java.

How can I handle edge cases like division by zero or integer overflow when dividing integers in my code?

You can delve into best practices for handling division by zero, checking for overflow conditions, and using techniques like bit manipulation or binary search to handle large numbers more efficiently.

What are some alternative approaches to integer division beyond simple arithmetic operators?

We can explore alternative methods for dividing integers, such as using bit manipulation, binary search, or other mathematical techniques, and discuss their advantages and limitations in terms of performance and precision.

Conclusion

So, this blog discussed the problem of Divide Two Integers using 3 different approaches, discussing each approach's time and space complexity. To learn more, head over right now to Coding Ninjas Studio to practice problems on topics like Brute Force, Binary Search, and Bit Manipulation, and crack your interviews like a Ninja!

Practicing a bunch of questions is not enough in this competitive world. So go check out where you stand among your peers by taking our mock tests and see which areas need improvement.

In case of any comments or suggestions, feel free to post them in the comments section.

Previous article
Number of Steps to Reduce a Number in Binary Representation to One
Next article
Binary Numbers of N digits
Live masterclass