-
Notifications
You must be signed in to change notification settings - Fork 15
/
Division Without Using Operator_anvai0304
56 lines (43 loc) · 1.7 KB
/
Division Without Using Operator_anvai0304
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def divide_with_precision(dividend, divisor, precision=2):
# Handle division by zero
if divisor == 0:
return "Division by zero is undefined"
# Determine the sign of the result
sign = -1 if (dividend < 0) ^ (divisor < 0) else 1
# Work with positive values for easier calculation
dividend, divisor = abs(dividend), abs(divisor)
# Initialize quotient
quotient = 0
factor = 10 ** precision # Factor to shift decimals
# Perform the division using bit manipulation for the integer part
while dividend >= divisor:
temp, multiple = divisor, 1
# Double the divisor until it exceeds dividend
while dividend >= (temp << 1):
temp <<= 1
multiple <<= 1
# Subtract the largest multiple of divisor from dividend
dividend -= temp
quotient += multiple
# Now handle the fractional part by multiplying dividend by 10^precision
dividend *= factor
# Perform division for the fractional part
fractional_part = 0
while dividend >= divisor:
temp, multiple = divisor, 1
# Double the divisor until it exceeds dividend
while dividend >= (temp << 1):
temp <<= 1
multiple <<= 1
# Subtract the largest multiple of divisor from dividend
dividend -= temp
fractional_part += multiple
# Combine integer and fractional parts
result = quotient + fractional_part / factor
# Apply the sign to the result
return sign * result
# Example Usage
dividend = 25
divisor = 3
result = divide_with_precision(dividend, divisor, precision=2)
print(f"{dividend} / {divisor} = {result:.2f}")