Solution for Counting Gems problem