a-conjecture-of-mine

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

Main.java (1730B)

 1 // The following program is a simple test for the following conjecture:
 2 
 3 // Let S: N -> N be the sum of the digits of a positive integer.
 4 // For all A and B in N, S(A + B) = S(A) + S(B) - 9k, where k is an integer.
 5 
 6 import java.util.InputMismatchException;
 7 
 8 public class Main {
 9     private static final int SUCCESS = 0;
10     private static final int FAIL = 1;
11     private static final int INVALID_INPUT = 2;
12 
13     public static void main(String[] args) {
14         try {
15             int max = Integer.parseInt(args[0]);
16             if (max <= 0) throw new IllegalArgumentException();
17 
18             if (counterexample(max)) {
19                 System.exit(FAIL);
20             } else {
21                 System.exit(SUCCESS);
22             }
23         } catch (Exception error) {
24             System.exit(INVALID_INPUT);
25         }
26 
27     }
28 
29     private static Boolean counterexample(int max) {
30         int[] sum = getSums(max);
31 
32         for (int a = 0; a <= max; a++)
33             for (int b = a; b <= max; b++) {
34                 int diff = sum[a + b] - sum[a] - sum[b];
35 
36                 if (diff % 9 != 0)
37                     return true;
38             }
39 
40         return false;
41     }
42 
43     private static int[] getSums(int max) {
44         int maxRange = 2 * max + 1;
45         int[] sums = new int[maxRange];
46 
47         for (int i = 0; i < maxRange; i++)
48             sums[i] = sumDigits(i);
49 
50         return sums;
51     }
52 
53     /**
54      * Calculates the sum of the digits of a positive integer.
55      */
56     private static int sumDigits(int n) {
57         int num = n, sum = 0;
58 
59         while (num > 0) {
60             sum += num % 10;
61             num /= 10;
62         }
63 
64         return sum;
65     }
66 }
67