a-conjecture-of-mine

An exercise on polyglossy: the same problem solved on multiple languages

Commit
11684a6cca2bd4dc18173a3f2635dc4878a7c0e5
Parent
364f3869791e00048bb41663581f98331bff34e6
Author
Pablo Escobar Gaviria <gark.garcia@protonmail.com>
Date

Cleaned the Kotlin implementation.

Diffstat

3 files changed, 8 insertions, 26 deletions

Status File Name N° Changes Insertions Deletions
Modified Go/main.go 2 1 1
Modified Kotlin/bin.jar 0 0 0
Modified Kotlin/main.kt 32 7 25
diff --git a/Go/main.go b/Go/main.go
@@ -98,7 +98,7 @@ func counterIter(it iter, sums *[]int, c chan bool) {
 }
 
 func getSums(max uint) []int {
-	maxRange := 2*max + 1
+	maxRange := 2 * max + 1
 	sums := make([]int, maxRange)
 
 	for i := range sums {
diff --git a/Kotlin/bin.jar b/Kotlin/bin.jar
Binary files differ.
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
-    }
-}