Solution of Problem #5 (Not in Perl/Python because it will be very slow - like 1min or more?)