Scoop API

scoop:scoop.math:0.1.0

src/internal/integer/multiplication.scoop

Selected production source · src/internal/integer/multiplication.scoop

1// Algorithms adapted from num-bigint 0.5.1 (MIT); see sysroot/vendor/num-bigint.
2package scoop.math
4// Schoolbook below the crossover, Karatsuba above it; unbalanced operands split only the longer side.
5internal fun magnitudeMultiply(a: Array<UInt>, b: Array<UInt>): Array<UInt> {
6 val shorter = if (a.size <= b.size) a else b
7 val longer = if (a.size <= b.size) b else a
8 if (shorter.size <= 64L) return magnitudeMultiplySchoolbook(shorter, longer)
9 val result = MutableArray<UInt>(addExact(a.size, b.size)) { _ -> 0u }
10 if (longer.size / 2L >= shorter.size) {
11 val split = longer.size / 2L
12 magnitudeAccumulate(result, magnitudeMultiply(shorter, magnitudeSlice(longer, 0L, split)), 0L)
13 magnitudeAccumulate(result, magnitudeMultiply(shorter, magnitudeSlice(longer, split, longer.size)), split)
14 } else {
15 val split = shorter.size / 2L
16 val a0 = magnitudeSlice(shorter, 0L, split)
17 val a1 = magnitudeSlice(shorter, split, shorter.size)
18 val b0 = magnitudeSlice(longer, 0L, split)
19 val b1 = magnitudeSlice(longer, split, longer.size)
20 val low = magnitudeMultiply(a0, b0)
21 val high = magnitudeMultiply(a1, b1)
22 val middle = magnitudeSubtract(magnitudeSubtract(magnitudeMultiply(magnitudeAdd(a0, a1), magnitudeAdd(b0, b1)), low), high)
23 magnitudeAccumulate(result, low, 0L)
24 magnitudeAccumulate(result, middle, split)
25 magnitudeAccumulate(result, high, split * 2L)
26 }
27 return magnitudeSnapshot(result)
30private fun magnitudeSlice(words: Array<UInt>, start: Long, end: Long): Array<UInt> {
31 var count = end - start
32 while (count > 0L && words[start + count - 1L] == 0u) count -= 1L
33 return Array<UInt>(count) { index -> words[start + index] }
36private fun magnitudeAccumulate(destination: MutableArray<UInt>, value: Array<UInt>, offset: Long) {
37 var carry = 0uL
38 var index = 0L
39 while (index < value.size || carry != 0uL) {
40 val sum = destination[offset + index].toULong() + magnitudeWord(value, index).toULong() + carry
41 destination[offset + index] = sum.toUInt()
42 carry = sum shr 32L
43 index += 1L
44 }