/** * Beispiele 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 */ import Foundation struct AuD_01_03_Riddle { static func Riddle(n: Int, m: Int) -> Int { var x = n var y = m var p = 0 print(" n | m | x | y | p ") print("-----+-------+------+------+-----") while (x >= 1) { print(String(format:"%4.0d | %4.0d | %4.0d | %4.0d | %4.0d", n, m, x, y, p)) assert(n * m == x * y + p) if (x % 2 == 0) { x = x / 2 } else { p = p + y x = (x - 1) / 2 } y = 2 * y } print(String(format:"%4.0d | %4.0d | %4.0d | %4.0d | %4.0d", n, m, x, y, p)) return p } static func product(n: Int, m:Int) -> Int { var x = n var p = 0 print( " n | m | x | p ") print( "-----+-------+------+-----") while (x >= 1) { print(String(format:"%4.0d | %4.0d | %4.0d | %4.0d", n, m, x, p)) assert(n * m == x * m + p) p = p + m x = x - 1 } print(String(format:"%4.0d | %4.0d | %4.0d | %4.0d", n, m, x, p)) return p } static func run() { let prod1 = product(n:5, m:6) print() let prod2 = Riddle(n:5, m:6) print() print("5*6 = \(prod1) = \(prod2)") } }