Placing pow outside the Ring interface.

This commit is contained in:
zhelenskiy 2021-05-12 04:58:48 +03:00
parent b4e47494fc
commit ed86a31c50
2 changed files with 15 additions and 13 deletions

View File

@ -250,21 +250,21 @@ public interface Ring<T> : Group<T>, RingOperations<T> {
* neutral operation for multiplication * neutral operation for multiplication
*/ */
public val one: T public val one: T
}
public fun T.pow(exponent: ULong): T = when { public fun <T> Ring<T>.pow(base: T, exponent: ULong): T = when {
this == zero && exponent > 0UL -> zero this == zero && exponent > 0UL -> zero
this == one -> this this == one -> base
this == -one -> powWithoutOptimization(exponent % 2UL) this == -one -> powWithoutOptimization(base, exponent % 2UL)
else -> powWithoutOptimization(exponent) else -> powWithoutOptimization(base, exponent)
} }
private fun T.powWithoutOptimization(exponent: ULong): T = when (exponent) { private fun <T> Ring<T>.powWithoutOptimization(base: T, exponent: ULong): T = when (exponent) {
0UL -> one 0UL -> one
1UL -> this 1UL -> base
else -> { else -> {
val pre = powWithoutOptimization(exponent shr 1).let { it * it } val pre = powWithoutOptimization(base, exponent shr 1).let { it * it }
if (exponent and 1UL == 0UL) pre else pre * this if (exponent and 1UL == 0UL) pre else pre * base
}
} }
} }

View File

@ -98,6 +98,8 @@ public class BigInt internal constructor(
else -> BigInt(sign, multiplyMagnitudeByUInt(magnitude, other)) else -> BigInt(sign, multiplyMagnitudeByUInt(magnitude, other))
} }
public fun pow(other: ULong): BigInt = BigIntField { pow(this@BigInt, other) }
public operator fun times(other: Int): BigInt = when { public operator fun times(other: Int): BigInt = when {
other > 0 -> this * kotlin.math.abs(other).toUInt() other > 0 -> this * kotlin.math.abs(other).toUInt()
other != Int.MIN_VALUE -> -this * kotlin.math.abs(other).toUInt() other != Int.MIN_VALUE -> -this * kotlin.math.abs(other).toUInt()