Last active
November 24, 2015 19:32
-
-
Save fancellu/114d84d1b211339a5a41 to your computer and use it in GitHub Desktop.
Karatsuba solution in Scala. Works with negative numbers also.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Karatsuba solution in Scala. Works with negative numbers also. | |
// https://en.wikipedia.org/wiki/Karatsuba_algorithm | |
object Karatsuba { | |
import scala.math._ | |
def split(x:Int, y:Int)={ | |
val absx=abs(x) | |
val absy=abs(y) | |
val m=max(absx.toString.length(),absy.toString.length()) | |
val xpadded=s"%0${m}d".format(absx) | |
val ypadded=s"%0${m}d".format(absy) | |
val xpbits=xpadded.splitAt(m/2) | |
val ypbits=ypadded.splitAt(m/2) | |
val polx=signum(x) | |
val poly=signum(y) | |
((xpbits._1.toInt*polx,xpbits._2.toInt*polx), | |
(ypbits._1.toInt*poly,ypbits._2.toInt*poly),m-m/2) | |
} | |
def multiply(x: Int, y: Int): Int = { | |
if (abs(x)<10||abs(y)<10) x * y | |
else { | |
val ((a,b),(c,d),rest) = split(x,y) | |
val ac= multiply(a,c) | |
val bd= multiply(b,d) | |
val ad_plus_bc= multiply(a + b, c + d) - ac - bd | |
val _10rest = pow(10, rest).toInt | |
val _10rest2 = _10rest*_10rest | |
_10rest2*ac + _10rest*ad_plus_bc + bd | |
} | |
} | |
assert(multiply(5678, 1234)==7006652) | |
assert(multiply(131,46)==6026) | |
assert(multiply(123400,-10)== -1234000) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment