Problem 95: Amicable chains

The proper divisors of a number are all the divisors excluding the number itself.
For example, the proper divisors of 28 are 1, 2, 4, 7, and 14. As the sum of these divisors is equal to 28, we call it a perfect number.

Interestingly the sum of the proper divisors of 220 is 284 and the sum of the proper divisors of 284 is 220, forming a chain of two numbers.
For this reason, 220 and 284 are called an amicable pair.

Perhaps less well known are longer chains. For example, starting with 12496, we form a chain of five numbers:

12496 → 14288 → 15472 → 14536 → 14264 (→ 12496 → ...)

Since this chain returns to its starting point, it is called an amicable chain.

Find the smallest member of the longest amicable chain with no element exceeding one million.

My Algorithm

A pre-computation step creates a container divsum such that divsum[x] is the sum of all proper divisors of x.
My function getSum() from problem 21 produces the correct sum of all proper divisors but turns out to be too slow,
therefore I searched the web for faster algorithms and found this one:
1. split a number into its prime factors x = p_1^{e_1} * p_2^{e_2} * ...
where p_1, p_2, ... are the primes and e_1, e_2, ... how often they appear in x (=exponents), for example 96 = 2^5 * 3^1
2. then the sum of all divisors is (2^0 + 2^1 + 2^2 + 2^3 + 2^4 + 2^5) * (3^0 + 3^1) = 252
3. but since we need only the proper divisors instead of all divisors (which include the number itself): 252 - 96 = 156
→ divsum[96] = 156

The chain algorithm appends chain[i] = divsum[chain[i - 1]] until:
1. it's the initial number, then an amicable chain was found or
2. it's a number lower than the initial number → abort because we should have seen this loop before, when we processed that lower number or
3. it's a number above the limit → abort according to problem description ("no element exceeding one million") or
4. it's a number that is already part of the chain → a loop

If the chain is longer than anything before than its first element is stored in smallestMember (it must be the first element of the chain).

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 10 | ./95

Output:

(please click 'Go !')

(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>

intmain()

{

unsignedint limit;

std::cin>> limit;

// the usual prime sieve

std::vector<unsignedint> primes;

primes.push_back(2);

for (unsignedint i = 3; i <= limit; i += 2)

{

bool isPrime = true;

// test against all prime numbers we have so far (in ascending order)

for (auto p : primes)

{

// next prime is too large to be a divisor ?

if (p*p > i)

break;

// divisible ? => not prime

if (i % p == 0)

{

isPrime = false;

break;

}

}

// yes, we have a prime number

if (isPrime)

primes.push_back(i);

}

// initial mapping of each number to its proper divisor's sum

std::vector<unsignedint>divsum(limit + 1, 0);

for (unsignedint i = 2; i <= limit; i++)

{

unsignedint sum = 1;

unsignedint reduce = i;

for (auto p : primes)

{

// note: reduce itself might be prime in the end

if (p*p > reduce)

break;

// divide by all primes

unsignedint factor = 1;

while (reduce % p == 0)

{

reduce /= p;

// add 1 to each exponent, e.g. p^0 + p^1 becomes p^1 + p^2

factor *= p;

// add a new term p^0

factor++;

}

sum *= factor;

}

// if a large prime was left over

if (reduce > 1 && reduce < i)

sum *= reduce + 1;

// subtract number itself if it isn't a prime

if (sum > 1)

sum -= i;

divsum[i] = sum;

}

// loop until numbers are mapped to themselves (or get stuck in a loop)

unsignedint longestChain = 0;

unsignedint smallestMember = limit;

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

{

// re-use the same vector over and over again to avoid memory re-allocations

Changelog

Hackerrank

Difficulty

30%
Project Euler ranks this problem at 30% (out of 100%).

Hackerrank describes this problem as medium.

Note:Hackerrank has strict execution time limits (typically 2 seconds for C++ code) and often a much wider input range than the original problem.In my opinion, Hackerrank's modified problems are usually a lot harder to solve. As a rule thumb: brute-force is rarely an option.

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 !