27 Apr 2014

Division without operator

Problem Statement:
      Find the quotient without using the operator ('/').

Solution:
Run Source Code

Below is the implementation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
 * Division without using '/' operator
 * @author PRATEEK
 */
public class Division {

 public static int division(int dividend, int divisor) {
  if (divisor == 0)
   throw new ArithmeticException("Division by Zero");

  boolean isPositive = true; // flag for negative number

  if (dividend < 0) {
   isPositive = !isPositive; // toggle flag, i.e.negative
   dividend *= -1; // make divident positive
  }

  if (divisor < 0) {
   isPositive = !isPositive;
   divisor *= -1;
  }

  int temp, mul, result = 0;
  for (; dividend >= divisor; dividend -= temp >> 1, result += mul >> 1)
   for (mul = 1, temp = divisor; temp <= dividend; temp <<= 1, mul <<= 1);
 
  return result;
 }

 public static void main(String[] args) {
  int numerator = 56;
  int denominator = 5;
  int ans = division(numerator, denominator);
  System.out.println(numerator+"/"+denominator+"="+ans);
 }
}

Download Source Code
Please comment and post your suggestions.
Happy Coding !! :)

1 comment:

  1. The concept of performing division without using an operator is fascinating and clever! For those looking to enhance their coding skills, AmbitionHost is a fantastic resource to explore.

    ReplyDelete