scoop:scoop.math:0.1.0
src/internal/integer/montgomery.scoop
Selected production source · src/internal/integer/montgomery.scoop
1
package scoop.math3
// REDC with an odd modulus. Every operand and result is in [0, modulus).4
private fun montgomeryMultiply(a: Array<UInt>, b: Array<UInt>, modulus: Array<UInt>, inverse: UInt): Array<UInt> {5
val n = modulus.size6
val words = MutableArray<UInt>(addExact(multiplyExact(n, 2L), 1L)) { _ -> 0u }7
var i = 0L8
while (i < a.size) {9
var carry = 0uL10
var j = 0L11
while (j < b.size) {12
val product = a[i].toULong() * b[j].toULong() + words[i + j].toULong() + carry13
words[i + j] = product.toUInt()14
carry = product shr 32L15
j += 1L16
}17
words[i + b.size] = carry.toUInt()18
i += 1L19
}20
i = 0L21
while (i < n) {22
val multiplier = words[i] * inverse23
var carry = 0uL24
var j = 0L25
while (j < n) {26
val product = multiplier.toULong() * modulus[j].toULong() + words[i + j].toULong() + carry27
words[i + j] = product.toUInt()28
carry = product shr 32L29
j += 1L30
}31
var position = i + n32
while (carry != 0uL) {33
val sum = words[position].toULong() + carry34
words[position] = sum.toUInt()35
carry = sum shr 32L36
position += 1L37
}38
i += 1L39
}40
val result = magnitudeSnapshot(Array<UInt>(n + 1L) { index -> words[index + n] })41
return if (magnitudeCompare(result, modulus) >= 0L) magnitudeSubtract(result, modulus) else result42
}44
internal fun integerMontgomeryPow(base: IntegerStorage, exponent: Array<UInt>, modulus: IntegerStorage): IntegerStorage {45
val divisor = integerMagnitude(modulus)46
var reciprocal = 1u47
var iteration = 048
while (iteration < 5) { reciprocal *= 2u - divisor[0L] * reciprocal; iteration += 1 }49
val inverse = 0u - reciprocal50
val radixBits = multiplyExact(divisor.size, 32L)51
var result = integerMagnitude(integerMod(integerShift(IntegerStorage.Small(1L), radixBits, true), modulus))52
val power = integerMagnitude(integerMod(integerShift(base, radixBits, true), modulus))53
var bit = magnitudeBits(exponent)54
while (bit > 0L) {55
bit -= 1L56
result = montgomeryMultiply(result, result, divisor, inverse)57
if ((exponent[bit / 32L] and (1u shl (bit % 32L))) != 0u) result = montgomeryMultiply(result, power, divisor, inverse)58
}59
return integerFromMagnitude(false, montgomeryMultiply(result, Array<UInt>(1L) { _ -> 1u }, divisor, inverse))60
}