Solution for problem UVa 507