Based on Project Euler problem 13