package kapitel_01 /** * Beispiel aus * * - Algorithmen und Datenstrukturen für Dummies * - von Andreas Gogol-Döring und Thomas Letschert * - Verlag Wiley-VCH; Oktober 2019 * - Kapitel 1, Das sind Algorithmen * * @author A. Gogol-Döring, Th. Letschert */ object AuD_01_03_Riddle_App extends App { def Riddle(n: Int, m:Int): Int = { var x = n var y = m var p = 0 println(" n | m | x | y | p ") println(s"-----+-------+------+------+-----") while (x >= 1) { println(f"$n%4.0f | $m%4.0f | $x%4.0f | $y%4.0f | $p%4.0f") assert(n * m == x * y + p) if (x % 2 == 0) { x = x / 2 } else { p = p + y x = (x - 1) / 2 } y = 2 * y } println(f"$n%4.0f | $m%4.0f | $x%4.0f | $y%4.0f | $p%4.0f") p } def product(n: Int, m:Int): Int = { var x = n var p = 0 println( " n | m | x | p ") println(s"-----+-------+------+-----") while (x >= 1) { println(f"$n%4.0f | $m%4.0f | $x%4.0f | $p%4.0f") assert(n * m == x * m + p) p = p + m x = x - 1 } println(f"$n%4.0f | $m%4.0f | $x%4.0f | $p%4.0f") p } val prod1 = product(5, 6) println() println(s"5*6 = $prod1") val prod2 = Riddle(5, 6) println() println(s"5*6 = $prod2") }