Problem 485: Maximum number of divisors

Let d(n) be the number of divisors of n.
Let M(n,k) be the maximum value of d(j) for n <= j <= n+k-1.
Let S(u,k) be the sum of M(n,k) for 1 <= n <= u-k+1.

You are given that S(1000, 10) = 17176.

Find S(100 000 000, 100 000).

My Algorithm

I needed to translate the short problem description into plain English (well, I'm German so actually it wasn't English ...):
to find S(1000, 10) I have to create 990 blocks with 10 elements each:\{ d(1), d(2), ..., d(10) \},\{ d(2), d(3), ..., d(11) \},\{ d(3), d(4), ..., d(12) \},
...\{ d(991), d(992), ..., d(1000) \}
and add the maximum values of all those 990 blocks.

My first step is to fill the container numDivisors with d(1), d(2), ..., d(10^8).
The maximum value is 768 so an unsigned short is sufficient - but it still requires 200 MByte RAM.

I implemented two algorithms to compute the number of divisors of n:countDivisorsSlow is based on trial division: it divides n by every number between 1 and n and counts how often the remainder is zero.
That's pretty fast if n is small (well, even 10^6 is almost okay) but much too slow for 10^8.

countDivisors needs only one second to perform the same task:
if the number n is factorized into its prime factors n = {p_1}^e_1 * {p_2}^e_2 * {p_3}^e_3 * ...
then the number of divisors is d(n) = (e_1 + 1) * (e_2 + 1) * (e_3 + 1) * ...
My first step is to find all prime numbers below 10^8 (see below for a significant optimization / chapter "Note").
Then all d(n) are initialized with 1 and:

iterate over all multiples m of 2^1 = 2, multiply d(m) by 1+1=2

iterate over all multiples m of 2^2 = 4, multiply d(m) by 2+1=3 and divide by 1+1=2 (that's an undo of the previous step)

iterate over all multiples m of 2^3 = 8, multiply d(m) by 3+1=4 and divide by 2+1=3 (that's an undo of the previous step)

iterate over all multiples m of 2^4 = 16, multiply d(m) by 4+1=5 and divide by 3+1=4 (that's an undo of the previous step)

... and so on, until 2^x > 10^8

repeat the same procedure for all other primes 3, 5, 7, 11, ...

Now that I have d(n), I need to find the maximums of each blocks. I wrote two algorithms to find them:

the obvious bruteForce() algorithm with two nested loops has 10^8 * 10^5 = 10^13 iterations and is too slow.

a smarter algorithm can do the same job in just 10^8 iterations !

In search(), each iteration updates mostRecent[d(n)] with the current position n (and enlarges mostRecent if required).
Zero is more or less a dummy element and the whole algorithm still works if I omit it but it simplifies index calculations a lot.
Only once it causes minor problems: the maximum number is the size of mostRecent minus 1.

If an element of mostRecent is too far away, that means if its value is more than blockSize away from the current position, then it becomes invalid.
That's only important for the largest indices of mostRecent: they will be removed, thus shrinking mostRecent.

Alternative Approaches

The whole algorthm could be rewritten to process the data in chunks instead of all 100 million at once.
Memory consumption will drop considerably and I expect performance to remain about the same (maybe a tiny bit slower).
But the code size will grow considerably and become less reabable.

In conclusion, pretty much every maximum d(n) of a block has typically very small prime factors.
Assuming that all prime factors of a maximum d(n) are less than sqrt{10^8} = 10^4, my code will still find the correct result for S(10^8, 10^5).
However, this "square-root" assumption isn't always true: it fails for S(1000, 10) (the problem is the small blockSize).

The less primes I use as prime factors in countDivisors the faster the code becomes (at the risk of being off, depending on blockSize).
I manually looked for the smallest "valid" value for primeLimit for S(10^8, 10^5) and it turned out to be 107.
Using this parameter cuts down the execution time from 1.8 to 1.1 seconds.

Interactive test

You can submit your own input to my program and it will be instantly processed at my server:

Input data (separated by spaces or newlines):

This is equivalent toecho "1000 10" | ./485

Output:

(please click 'Go !')

Note: the original problem's input 100000000 100000cannot be enteredbecause just copying results is a soft skill reserved for idiots.

(this interactive test is still under development, computations will be aborted after one second)

My code

… was written in C++11 and can be compiled with G++, Clang++, Visual C++. You can download it, too.

#include<iostream>

#include<vector>

#include<algorithm>

#include<cmath>

// store the number of divisors for the first 100 million numbers

typedefunsignedshort Number; // => 200 MByte

std::vector<Number> numDivisors;

// slow trial division

voidcountDivisorsSlow(unsignedint limit)

{

// zero has no divisors

numDivisors = { 0 };

// process all numbers 1..10^8

for (unsignedint current = 1; current <= limit; current++)

{

Number count = 0;

// trial division of all numbers <= sqrt(current)

for (unsignedint divisor = 1; divisor*divisor <= current; divisor++)

{

// divisible ?

if (current % divisor != 0)

continue;

count++; // one divisor if i^2 = x

if (divisor*divisor != current) // or two if not (it's i and x/i)

count++;

}

numDivisors.push_back(count);

}

}

// similar to a prime sieve, much faster

voidcountDivisors(unsignedint limit, unsignedint primeLimit = 0)

{

numDivisors.resize(limit + 1, 1);

// zero has no divisors

numDivisors[0] = 0;

// accurate algorithm by default

if (primeLimit == 0)

primeLimit = limit;

// simple prime sieve (trial division because it has the shortest/most simple implementation)

Those links are just an unordered selection of source code I found with a semi-automatic search script on Google/Bing/GitHub/whatever.
You will probably stumble upon better solutions when searching on your own.
Maybe not all linked resources produce the correct result and/or exceed time/memory limits.

Heatmap

Please click on a problem's number to open my solution to that problem:

green

solutions solve the original Project Euler problem and have a perfect score of 100% at Hackerrank, too

yellow

solutions score less than 100% at Hackerrank (but still solve the original problem easily)

gray

problems are already solved but I haven't published my solution yet

blue

solutions are relevant for Project Euler only: there wasn't a Hackerrank version of it (at the time I solved it) or it differed too much

orange

problems are solved but exceed the time limit of one minute or the memory limit of 256 MByte

red

problems are not solved yet but I wrote a simulation to approximate the result or verified at least the given example - usually I sketched a few ideas, too

black

problems are solved but access to the solution is blocked for a few days until the next problem is published

[new]

the flashing problem is the one I solved most recently

I stopped working on Project Euler problems around the time they released 617.

The 310 solved problems (that's level 12) had an average difficulty of 32.6&percnt; at Project Euler and
I scored 13526 points (out of 15700 possible points, top rank was 17 out of &approx;60000 in August 2017)
at Hackerrank's Project Euler+.

My username at Project Euler is stephanbrumme while it's stbrumme at Hackerrank.

Copyright

I hope you enjoy my code and learn something - or give me feedback how I can improve my solutions.All of my solutions can be used for any purpose and I am in no way liable for any damages caused.You can even remove my name and claim it's yours. But then you shall burn in hell.

The problems and most of the problems' images were created by Project Euler.Thanks for all their endless effort !!!

more about me can be found on my homepage,
especially in my coding blog.
some names mentioned on this site may be trademarks of their respective owners.
thanks to the KaTeX team for their great typesetting library !