algorithm exercise with java