diff --git a/Kotlin/main.kt b/Kotlin/main.kt
@@ -18,7 +18,9 @@ fun main(args: Array<String>) {
val max = args[0].toInt()
if (max <= 0) throw IllegalArgumentException()
- if (counterexample(max, HashMap(max * 2))) exitProcess(FAIL)
+ val sumsCache = IntArray(2 * max + 1) { n -> sumDigits(n) }
+
+ if (counterexample(max, sumsCache)) exitProcess(FAIL)
else exitProcess(OK)
} catch (_: Exception) {
@@ -30,14 +32,10 @@ fun main(args: Array<String>) {
* Searches for a counterexample for the theorem in
* `{(a, b) in N^2 | a <= max, b <= a}`.
*/
-fun counterexample(max: Int, sums_cache: HashMap<Int, Int>): Boolean {
+fun counterexample(max: Int, sumsCache: IntArray): Boolean {
for (a in 0..max)
for (b in a..max) {
- val sumAB = sums_cache.getSum(a + b)
- val sumA = sums_cache.getSum(a)
- val sumB = sums_cache.getSum(b)
- val diff = sumAB - sumA - sumB
-
+ val diff = sumsCache[a + b] - sumsCache[a] - sumsCache[b]
if (diff % 9 != 0) return true
}
@@ -47,9 +45,9 @@ fun counterexample(max: Int, sums_cache: HashMap<Int, Int>): Boolean {
/**
* Calculates the sum of the digits of a positive integer.
*/
-fun sum(n: Int): Int {
+fun sumDigits(n: Int): Int {
var sum = 0
- var num = n.absoluteValue
+ var num = n
while (num > 0) {
sum += num % 10
@@ -59,19 +57,3 @@ fun sum(n: Int): Int {
return sum
}
-/**
- * Attempts to lookup the sum of the digits of `key`.
- *
- * If the lookup fails, calculate the sum of the digits
- * of `key`, store it in the map and return it.
- */
-fun HashMap<Int, Int>.getSum(key: Int): Int {
- if (containsKey(key)) {
- return getValue(key)
- } else {
- val value = sum(key)
- put(key, value)
-
- return value
- }
-}