Optimize solution to problem #47 by caching prime factors