Jump to content

Long multiplication: Difference between revisions

Kotlin entry
m (added whitespace to the task's preamble, used superscripts instead of a "hat" to show exponentiation.)
(Kotlin entry)
Line 2,439:
$ jq -n -f Long_multiplication.jq
"340282366920938463463374607431768211456"
 
=={{header|Kotlin}}==
{{trans|Java}}
<lang scala>fun String.toDigits() = mapIndexed { i, c ->
if (!c.isDigit())
throw IllegalArgumentException("Invalid digit $c found at position $i")
c - '0'
}.reversed()
 
operator fun String.times(n: String): String {
val left = toDigits()
val right = n.toDigits()
val result = IntArray(left.size + right.size)
 
right.mapIndexed { rightPos, rightDigit ->
var tmp = 0
left.indices.forEach { leftPos ->
tmp += result[leftPos + rightPos] + rightDigit * left[leftPos]
result[leftPos + rightPos] = tmp % 10
tmp /= 10
}
var destPos = rightPos + left.size
while (tmp.toInt() != 0) {
tmp += (result[destPos].toLong() and 0xFFFFFFFFL).toInt()
result[destPos] = tmp % 10
tmp /= 10
destPos++
}
}
 
val stringResultBuilder = StringBuilder(result.size)
result.reversed().mapIndexed { i, digit ->
if (digit != 0 || stringResultBuilder.length > 0)
stringResultBuilder.append(('0' + digit).toChar())
}
return stringResultBuilder.toString()
}
 
fun main(args: Array<out String>) {
println("18446744073709551616" * "18446744073709551616")
}</lang>
=={{header|Liberty BASIC}}==
 
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.