Problem #159 asks:
The function mdrs(n) gives the maximum Digital Root Sum of \(n\). So \(\text{mdrs}(24)=11\).
Find \(\text{mdrs}(n)\) for \(1\lt n\lt 1,000,000\).
First we need to know that the Digital root of a number is equal to
$$
f(x) = \left\{
\begin{array}{lr}
n \pmod{9} & : n \neq 0 \pmod{9}\\
9 & : n = 0 \pmod{9}
\end{array}
\right.
$$
We then need the simple relations that \(\text{mdrs}(n) = n\) for prime \(n\), otherwise we look at the list of divisors such that \( a*b = n\) and apply \(\text{mdrs}(n) = Max(\text{mdrs}(a) + \text{mdrs}(b), \text{drs}[n])\) for each pair a&b. setting this up can be done in two ways: 1) Factor the number and generate each MDRS individually which for the number range we’re looking at isn’t too bad or 2) a dynamic programming approach which avoids factoring and creates all the MDRS’s in one go so we just have to add them up. The solution below uses the second approach, runs in about 3 tenths of a second for the given Maximum.
using System;
using System.Diagnostics;
using System.Linq;
namespace Problem159
{
class Program
{
private const long Max = 1000000;
static void Main()
{
var drs = new long[Max];
var sw = new Stopwatch();
sw.Start();
for (long i = 2;i < Max; i++)
{
if (drs[i] == 0)
drs[i] = i%9 ==0? 9 : i%9;
else if (drs[i]<10)
{
long c = i % 9 == 0 ? 9 : i % 9;
drs[i] = Math.Max(c, drs[i]);
}
long cur = i;
for (long fac = 2; fac <=i; fac++)
{
cur += i;
if (cur >= Max)
break;
drs[cur] = Math.Max(drs[i] + drs[fac], drs[cur]);
}
}
sw.Stop();
var sum = drs.Sum();
Console.WriteLine(sum);
Console.WriteLine(sw.Elapsed);
Console.ReadLine();
}
}
}