Scala中实现和Python一致的整数除法和整数求余,Python中实现和Scala一致的整数除法和整数求余
\[\color{black}{\text{In scala, it's weird to imitate/mimic `%` `//` of python, and vice versa.}}
\]
Scala中实现和Python一致的整数除法和整数求余
/*
Python's % operator returns a result with the same sign as the divisor, and // rounds towards negative infinity.
In Scala, % and / don't behave the same way. The % operator returns a result with the same sign as the dividend, and / performs truncating division, rounding towards zero.
*/
def pythonMod(a: Int, b: Int): Int = ((a % b) + b) % b
def pythonDiv(a: Int, b: Int): Int = {
if ((a > 0 && b > 0) || (a < 0 && b < 0)) a / b
else if (a % b == 0) a / b
else a / b - 1
}
Python中实现和Scala一致的整数除法和整数求余
def scala_div(x, y):
if y == 0:
raise ZeroDivisionError('division by zero')
elif (x < 0 and y < 0) or (x > 0 and y > 0):
return abs(x) // abs(y)
else:
return -(abs(x) // abs(y))
def scala_mod(x, y):
if y == 0:
raise ZeroDivisionError('modulo by zero')
elif x < 0:
return -(abs(x) % abs(y))
else:
return x % abs(y)