Divide two integers without *, / and % in C#. Learn how to divide two numbers with bitwise operators,’+ and _’ amd recursive functions.
Divide two integers without *, / and % in C#
For Example there are 2 numbers number1 and number2 where number1 = 11 and number2=3, then division of number1 and number2 is 3
i.e, number1/number2=11/3=3;
In the above example number1 is dividend, and number2 is divisor.
Note:
If number1 is less than the number2 then division of num1,num2 is 0
We can use bitwise operators to perform division operation.
Here is the example program to divide 2 numbers using bitwise left shift operator.
c# Example program- divide 2 numbers using bitwise operator.
STEP 1: perform multiplication operation with bitwise left shift operator until the number in the temp variable > num1 variable
STEP2 : perform addition operation until the number in the temp+num2 <=1
using System;
class Program
{
static void Main(string[] args)
{
int num1 = 11, num2 = 3, quotient = 1, temp;
temp = num2;
//STEP1
//if divisor number is less than the dividend number then
// the code in the if block will be executed
//else execute the code in the else bock
if (num2 <= num1)
{
int i = 1;
//perform multiplication operation with
//bitwise left shift operator
//until the number in the temp variable > num1 variable
while (((temp << i) - num1) < 0)
{
temp = num2 << i;
quotient = quotient << 1;
}
// perform addition operation
// until the number in the temp+num2 <=1
while ((temp + num2) <= num1)
{
temp = temp + num2;
quotient = quotient + 1;
}
}
else
{
//quotient is 0 if divisior is > dividend
quotient = 0;
}
Console.WriteLine("Division of 2 numbers " + num1 +
" and " + num2 + " = " + quotient);
}
}
Output
Division of 2 numbers 11 and 3 = 3
c# Example program using +,- operators
//subtract the dividend with divisior till dividend is
//lessthan or equal to divisior
class Program
{
static void Main(string[] args)
{
int num1 = 11, num2 = 3, quotient = 0;
if (num1 >= num2)
{
while (num1 >= num2)
{
//subtract the dividend with divisior till dividend is
//lessthan or equal to divisior
num1 = num1 - num2;
++quotient;
}
}
else
{
quotient = 0;
}
Console.WriteLine("Division of 2 numbers " + num1 +
" and " + num2 + " = " + quotient);
}
}
c# Example program using recursion
class Program
{
public int quotient = 0;
static void Main(string[] args)
{
int num1 = 11, num2 = 3, quotient;
Program p=new Program();
quotient= p.divide(num1,num2);
Console.WriteLine("Division of 2 numbers " + num1 +
" and " + num2 + " = " + quotient);
}
public int divide(int num1,int num2)
{
if (num1 < num2)
{
return 0;
}
else
{
return divide(num1 - num2, num2) + 1;
}
}
}