@@ -9,3 +9,81 @@ for (let j = 0; j < 100; j++) {
99}
1010
1111console . log ( '8 digits:' , slice_to_iterate . slice ( 0 , 8 ) . join ( '' ) ) ;
12+
13+
14+ /*
15+
16+ Here's the trick:
17+
18+ Let's say your 12 digits number is `123456789123`.
19+ Look at the table after you get past the "halfway point" down the list:
20+
21+ | # | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 1 | 2 | 3 |
22+ |----|------|------|------|------|------|------|------|------|------|------|------|------|
23+ | 1 | 1 | | -3 | | 5 | | -7 | | 9 | | -2 | |
24+ | 2 | | 2 | 3 | | | -6 | -7 | | | 1 | 2 | |
25+ | 3 | | | 3 | 4 | 5 | | | | -9 | -1 | -2 | |
26+ | 4 | | | | 4 | 5 | 6 | 7 | | | | | -3 |
27+ | 5 | | | | | 5 | 6 | 7 | 8 | 9 | | | |
28+ | 6 | | | | | | 6 | 7 | 8 | 9 | 1 | 2 | |
29+ | 7 | | | | | | | *7* | *8* | *9* | *1* | *2* | *3* |
30+ | 8 | | | | | | | | *8* | *9* | *1* | *2* | *3* |
31+ | 9 | | | | | | | | | *9* | *1* | *2* | *3* |
32+ | 10 | | | | | | | | | | *1* | *2* | *3* |
33+ | 11 | | | | | | | | | | | *2* | *3* |
34+ | 12 | | | | | | | | | | | | *3* |
35+
36+ Starting from row 7 on down, all the numbers are added together! No 0s, no -1s, just the numbers
37+ added.
38+
39+ Since our "offset" is more than halfway through our full list, we can just immediately jump to the offset
40+ and compute those numbers on down.
41+
42+ Now adding up all those numbers in the triangle is still a _lot._ But there is another trick!
43+
44+ Look at the very last number, 3. let's call it A.
45+
46+ Go up one row, we have 2 + (3). But wait, 3 is A. So we have 2 + A. Let's call that B.
47+
48+ Go up another row, we have 1 + 2 + (3) -> 1 + (2 + A) -> 1 + B. Call that C.
49+
50+ You see where this is going. Go up another row, 9 + 1 + 2 + (3),
51+ 9 + 1 + (2 + A) -> 9 + (1 + B) -> 9 + C. Call that D.
52+
53+ And so on.
54+
55+ The other trick is, we only need to store the last digit each time we start from the bottom
56+ and loop up.
57+
58+ Consider
59+
60+ n + ... = x_n n + x_n-1 = x_n
61+ d + c + b + a = x_4 d + x_3 = x_4
62+ c + b + a = x_3 => c + x_2 = x_3
63+ b + a = x_2 b + x_1 = x_2
64+ a = x_1 a = x_1
65+
66+ Let x_n = D_i..D_1D_0 , where D_n is a single digit.
67+ (x_n)mod 10 = D_0
68+ Let `l + x_n` be the next line up we want to add. So l is a single digit number.
69+ We only care about the last digit of all that addition, so I want to show that
70+ (l + x_n)mod 10 = (l + D_0)mod 10.
71+ From the "Addition Property" of modular arithmetic, we know that
72+ (a + b)mod_n = [(a)mod_n + (b)mod_n]mod_n
73+
74+ So, expanding (l + x_n)mod 10 is
75+
76+ (l + x_n)mod_10 = ((l)mod_10 + (x_n)mod_10)mod_10.
77+
78+ Well (l)mod_10 is just l, since l is less than 10.
79+
80+ = ((l) + (x_n)mod_10)mod_10.
81+
82+ Add (x_n)mod_10 = D_0
83+
84+ = (l + D0 )mod_10.
85+
86+ QED.
87+
88+
89+ */
0 commit comments