a-conjecture-of-mine

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

main.kt (1383B)

 1 package conjecture
 2 
 3 import kotlin.math.absoluteValue
 4 import kotlin.system.exitProcess
 5 import kotlin.collections.HashMap
 6 
 7 // The following program is a simple test for the following conjecture:
 8 
 9 // Let S: N -> N be the sum of the digits of a positive integer.
10 // For all A and B in N, S(A + B) = S(A) + S(B) - 9k, where k is an integer.
11 
12 val OK = 0
13 val FAIL = 1
14 val INVALID_INPUT = 2
15 
16 fun main(args: Array<String>) {
17     try {
18         val max = args[0].toInt()
19         if (max <= 0) throw IllegalArgumentException()
20 
21         val sumsCache = IntArray(2 * max + 1) { n -> sumDigits(n) }
22 
23         if (counterexample(max, sumsCache)) exitProcess(FAIL)
24         else exitProcess(OK)
25 
26     } catch (_: Exception) {
27         exitProcess(INVALID_INPUT)
28     }
29 }
30 
31 /**
32  * Searches for a counterexample for the theorem in
33  * `{(a, b) in N^2 | a <= max, b <= a}`.
34  */
35 fun counterexample(max: Int, sumsCache: IntArray): Boolean {
36     for (a in 0..max)
37         for (b in a..max) {
38             val diff = sumsCache[a + b] - sumsCache[a] - sumsCache[b]
39             if (diff % 9 != 0) return true
40         }
41 
42     return false
43 }
44 
45 /**
46  * Calculates the sum of the digits of a positive integer.
47  */
48 fun sumDigits(n: Int): Int {
49     var sum = 0
50     var num = n
51 
52     while (num > 0) {
53         sum += num % 10
54         num /= 10
55     }
56 
57     return sum
58 }
59