My 'brute force' solution in Python (my first programme in this language) with many if and loops. Poor performance but at least it produces the right answers.

Code in Python:

...