How to divide 2 numbers without using / operator in java ?
Answers
# Function to perform division (x / y) of two numbers x and y without
# using division operator in the code
def divide(x, y):
# handle divisibility by 0
if y == 0:
print("Error!!Divisible by 0")
exit(1)
# store sign of the result
sign = 1
if x * y < 0:
sign = -1
# convert both dividend and divisor to positive
x = abs(x)
y = abs(y)
# initialize quotient by 0
quotient = 0
# loop till dividend x is more than the divisor y
while x >= y:
x = x - y # perform reduction on dividend
quotient = quotient + 1 # increase quotient by 1
print("Remainder is", x)
return sign * quotient
# main function to perform division of two numbers
if __name__ == '__main__':
dividend = 22
divisor = -7
print("Quotient is", divide(dividend, divisor))
JAVA PROGRAM➛
Write a Java Program to divide two numbers without using /operator:-
_______________________________
Let input no. be x and y.
We all know that if x is completely divisible by y then reminder is 0.
Taking same logic,
we subtract y from x till the x>0 and using Counter we find that how many times it is subtracting.
That Counter is our desired output.
Restriction:-
Restriction:-This code is for those value of x and y only whose division value come in Integer not in Decimal.
______________________________
class divisionofnumber
{
public static void main(int x,int y)
{
int a =x,count=0;
if(x%y==0)
{
for(;x>0;x=x-y)
{
count++;
}// for end
System.out.println("When we divide "+a+" from "+y);
System.out.println("Answer is:-"+count);
} //if end
}// main() end
}// class end
_______________________________
Input:-
x=8
y=2
Output -
When we divide 8 from 2
Answer is:-4