\(909\) sums to \(18\), which sums to \(9\).
Find the best way to compute it for any positive \(n\), efficiently.
Test cases in Scala
Algorithm in Scala
4 lines of Scala (compatible versions 2.13 & 3.0), showing how concise Scala can be!
This involves a bit of mathematics to figure out - but we can get an \(O(1)\) solution here:
The sum of digits of sum of digits... is equal to that digit modulo 9; if we take a number that is composed of digits\(abcd\), which equals \(10^3 \times a + 10 ^ 2 \times b + 10 \times c + d\), and then using %/modulo 9 we get:\(a + b + c + d (\mod 9)\), which is also \(((a + b) (\mod 9) + (c + d) (\mod 9))(\mod 9)\). Combining with a modulo table, you will notice thatindeed for example \(8 + 7 = 15\), and applying modulo 9 on \(15\) gives us \(6\), which is precisely the sum of digits \(1\) and \(5\). (this is © from www.scala-algorithms.com)