Karatsuba added, 2 bugs are fixed #328

Merged
zhelenskiy merged 15 commits from dev into dev 2021-05-14 09:12:26 +03:00
2 changed files with 15 additions and 13 deletions
Showing only changes of commit ed86a31c50 - Show all commits

View File

@ -250,21 +250,21 @@ public interface Ring<T> : Group<T>, RingOperations<T> {
* neutral operation for multiplication
*/
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 == one -> this
this == -one -> powWithoutOptimization(exponent % 2UL)
else -> powWithoutOptimization(exponent)
this == one -> base
this == -one -> powWithoutOptimization(base, exponent % 2UL)
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
1UL -> this
1UL -> base
else -> {
val pre = powWithoutOptimization(exponent shr 1).let { it * it }
if (exponent and 1UL == 0UL) pre else pre * this
}
val pre = powWithoutOptimization(base, exponent shr 1).let { it * it }
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))
}
public fun pow(other: ULong): BigInt = BigIntField { pow(this@BigInt, other) }
public operator fun times(other: Int): BigInt = when {
other > 0 -> this * kotlin.math.abs(other).toUInt()
other != Int.MIN_VALUE -> -this * kotlin.math.abs(other).toUInt()